Rails 序列化器默认值

Rails serializer default value

我有一个简单的博客应用程序,用户可以在其中对文章进行投票。当用户登录到我的文章控制器中的 index 方法时,return 会出现一个附加列,指示 current_user 是否已为该文章投票。我使用原始 SQL 连接来执行此操作。

#app/controllers/articles_controller.rb
@articles = Article.joins("LEFT OUTER JOIN 
                        (SELECT * FROM article_votes 
                        WHERE article_votes.user_id = #{uid.id}) AS av
                        ON articles.id = av.article_id")
      .select("articles.*,CASE WHEN av.user_id IS NULL THEN 0 ELSE 1 END AS user_voted")
      .where(safe_params)
      .order(order)

render json: @articles

有时我想 return 在用户未登录时通过简单地调用以下方法从索引方法中获取文章。此数据没有 user_voted 计数,因此默认值为 0 是合适的。

#app/controllers/articles_controller.rb
@articles = Article.all
render json: @articles

然而,当我尝试这样做时,出现以下错误。

NoMethodError (undefined method `user_voted' for #<Article:0x007fa584b95808>):
  app/controllers/articles_controller.rb:80:in `index'

当我向序列化程序显式添加 user_voted 方法时,我遇到了类似的错误。

#app/serializers/article_serializer.rb
class ArticleSerializer < ActiveModel::Serializer
  attributes :id, :title, :subheading, :body, :user_voted
  has_one :user

  def user_voted
    object.user_voted ||= 0
  end
end


NoMethodError (undefined method `user_voted' for #<Article:0x0000000490aa98>):
  app/serializers/article_serializer.rb:13:in `user_voted'
  app/controllers/articles_controller.rb:80:in `index'

添加到Article型号:

def user_voted
  self['user_voted'] || 0
end

然后您可以从序列化程序中删除 user_voted