简体   繁体   中英

Activemodel serializer n+1 query

I have the following Activemodel Serializer which needs to be customised on the current_user (scope)

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

The problem I have is I need to find out if the user has voted on the question.

User.rb Model:

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

Is there any way to avoid the n+1 query problem?

Currently the query to fetch the questions is:

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

Thanks

To avoid N+1 query problem with answers, you should link them with user and do the eager loading.

Adding has_many :answers to user.rb, you can rewrite the method:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM