Activemodel序列化器n + 1查询

时间:2014-03-09 19:28:48

标签: ruby-on-rails activerecord active-model-serializers

我有以下需要在current_user(范围)上自定义的Activemodel Serializer

class QuestionSerializer < ActiveModel::Serializer

attributes :id, :question,
       :user_id, :voted,
       :created_at,
       :total_votes, :comments_count



has_many :choices
has_many :comments
has_many :categories
has_one :user

def total_votes
   object.answers_count
end

def voted
   if scope && scope.has_voted?(object)
    return true
   else
    return false
   end
end

end

我遇到的问题是我需要找出用户是否对此问题进行了投票。

User.rb型号:

def has_voted?(question)
Answer.where(:question_id => question.id, :user_id => self.id).exists?
end

有没有办法避免n + 1查询问题?

目前提取问题的查询是:

Question.includes(:choices, :user, :comments, :categories).order(:created_at)

谢谢

1 个答案:

答案 0 :(得分:-1)

要避免答案出现N + 1查询问题,您应该将它们与用户链接并进行预先加载。

添加has_many:对user.rb的回答,您可以重写方法:

def has_voted?(question)
  answers.where(:question_id => question.id).exists?
end