2017-05-28 32 views
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 
... 
+0

is voteed_for?如果你直接在控制器中調用它,你會工作嗎?你可以試試嗎? – Niklas

+0

編寫一個測試'FlagService'的單元測試。你也應該改變參數爲位置'def initialize(user,flaggable)'或必需的關鍵字參數'def initialize(user :, flaggable:)',因爲它們應該是非可選的,因爲服務沒有它們就無法工作。 – max

+0

@Niklas yep;在控制器中工作。它也似乎在該服務中工作,但對投票的任何更新都不會持續。 – lgants

回答

0
class User < ApplicationRecord 
    # ... 
    def flagged?(post) 
    voted_for? post, vote_scope: 'flag' 
    end 
end 

class FlagService 

    def initialize(user:, post:) 
    @user= user 
    @post = post 
    end 

    def process 
    if @user.flagged?(@post) 
     @post.unvote_by @user, vote_scope: 'flag' 
    else 
     @post.vote_by voter: @user, vote_scope: 'flag' 
    end 
    end 
end 

鑑於實際的代碼是如何參與一點我會問題爲什麼這應該被提取到一個服務,因爲它增加了一個額外的抽象層次。相反,您可能需要創建單獨的路線來標記/取消標記,以響應POSTDELETE