I’m using Rails 3.2.8, and have models
class Subject < ActiveRecord::Base
has_and_belongs_to_many :users
end
class User < ActiveRecord::Base
has_and_belongs_to_many :subjects
end
in the SubjectsController, index
@subjects = Subject.includes(:users).all
I use includes to do eager load, and In the view file, I want to display all users of a subject by this:
<%= subject.users.count if not subject.users.nil? %>
the problem is I got db hit for every subject when display user count, which I think is the N+1 Query problem
anything I missed or did wrong?
btw: I’m using MySQL
The
countmethod always generates SQL COUNT query. Since you have already loaded all the entries, try to uselengthto avoid extra query: