I have an issue with a N+1 in my User model that I'm not sure how to fix. The method is setup like this:
has_many :group_questions, through: :groups, source: :questions
has_many :question_participants, as: :questionable
has_many :questions, through: :question_participants
# Collection of Users questions
def all_questions
group = group_questions
personal = questions
all_questions = group + personal
end
it gathers questions related to a group that a User is in, but also personal questions directed to that person. Finally it merges them into one array.
The N+1's I'm getting are:
N+1 Query detected
User => [:group_questions]
Add to your finder: :includes => [:group_questions]
User => [:questions]
Add to your finder: :includes => [:questions]
happens on this line:
current_user.all_questions.any?
class User
scope :with_questions, -> { includes(:questions, :group_questions) }
def all_questions
# No need for variables if you only use them once!
group_questions + questions
end
end
def show
@user = User.with_questions.find(params[:id])
end
You could use default_scope
but it's not really a good idea because it will slow down the cases where you don't need the joined records.
I just saw your comment about getting the user from current_user
. Although loading everything in one query would be optimal overriding the user loading in the authentication logic is a mess for a marginal performance gain. Instead you can do it like this:
@user = User.eager_load(:questions, :group_questions)
.find(current_user.id)
eager_load
will force ActiveRecord to load the records upfront in a single query. Try playing around with joins
, includes
and eager_load
in the rails console and check the difference in the the resulting SQL queries.
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.