我使用Rails 3.2.8,並有模型Rails的:ActiveRecord的貪婪加載和N + 1查詢
class Subject < ActiveRecord::Base
has_and_belongs_to_many :users
end
class User < ActiveRecord::Base
has_and_belongs_to_many :subjects
end
在SubjectsController
,指數
@subjects = Subject.includes(:users).all
我使用包括做的渴望負載,並在視圖文件,我想這個顯示對象的所有用戶:
<%= subject.users.count if not subject.users.nil? %>
的問題是,我得到了分貝命中爲每subjec t當顯示用戶數,我認爲是N + 1查詢問題
什麼我錯過了或做錯了?
BTW:我使用的MySQL
我覺得@Yanhao是正確的subjects.users永遠不會是零的。 – fengd