0

我正在清理 rails 5 应用程序的控制器,并且我创建了一个服务来标记帖子。不幸的是,由于将acts_as_votable 辅助方法移动到服务中,所有标志都不起作用。任何想法为什么这不起作用?

应用程序/服务/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
...
4

1 回答 1

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

于 2017-05-29T02:05:25.990 回答