0
我正在清理rails 5應用程序的控制器,並且我創建了一個標記帖子的服務。不幸的是,自從將acts_as_votable幫助器方法移動到服務中後,沒有任何標誌正在工作。任何想法爲什麼這不起作用?重構Rails acts_as_votable gem進入服務
應用程序/服務/ flag_service.rb
class FlagService
def initialize(params)
@current_user = params[:current_user]
@post = params[:post]
end
def process
if previous_vote?
@post.vote_by :voter => @current_user, :vote_scope => 'flag'
elsif !previous_vote?
@post.unvote_by @current_user, :vote_scope => 'flag'
else
nil
end
end
private
def previous_vote?
@current_user.voted_for? @post, vote_scope: 'flag'
end
end
應用程序/控制器/ bursts_controller.rb
...
def flag
if FlagService.new({current_user: current_user, post: @post}).process
render(status: 201, json: @category.as_json({:only => [:id, :status, :name, :description, :slug, :title] }))
else
render(status: 400, json: @category.errors)
end
end
...
is voteed_for?如果你直接在控制器中調用它,你會工作嗎?你可以試試嗎? – Niklas
編寫一個測試'FlagService'的單元測試。你也應該改變參數爲位置'def initialize(user,flaggable)'或必需的關鍵字參數'def initialize(user :, flaggable:)',因爲它們應該是非可選的,因爲服務沒有它們就無法工作。 – max
@Niklas yep;在控制器中工作。它也似乎在該服務中工作,但對投票的任何更新都不會持續。 – lgants