나는 컨트롤러 json에서 서비스 객체를 사용하는 json api를 만들고 있는데, json을 올바르게 렌더링해야하는 서비스에서 무슨 일이 일어나고 있는지를 근거로합니다. 예제는 다음과 같습니다.상태를 반환하는 서비스 객체
star_service.rb
class Place::StarService
def initialize(params, user)
@place_id = params[:place_id]
@user = user
end
def call
if UserStaredPlace.find_by(user: user, place_id: place_id)
return #star was already given
end
begin
ActiveRecord::Base.transaction do
Place.increment_counter(:stars, place_id)
UserStaredPlace.create(user: user, place_id: place_id)
end
rescue
return #didn't work
end
return #gave a star
end
private
attr_reader :place_id, :user
end
places_controller.rb
def star
foo_bar = Place::Star.new(params, current_user).call
if foo_bar == #sth
render json: {status: 200, message: "sth"}
elsif foo_bar == #sth
render json: {status: 200, message: "sth"}
else
render json: {status: 400, message: "sth"}
end
내가 서비스 객체에서 일반 텍스트를 반환해야하거나 더 좋은 방법이 있다면 내 질문은 무엇입니까?
그래서 당신은 내가 서비스를 삭제 논리를 이동해야한다고 말하고있다 컨트롤러에? –
죄송합니다. 답변을 다시 생각하고 업데이트했습니다. 아니요, 서비스를 삭제할 필요가 없습니다. 서비스는 생명입니다 :) 서비스는 결과 또는 거짓을 반환합니다. 컨트롤러의 동작 (private 메서드 사용)은'false '가 아닌 경우 결과를 렌더링합니다. – VAD