我有这样的 has_many 关系:
class Event < ActiveRecord::Base
has_many :event_rows
...
end
class EventRow < ActiveRecord::Base
belongs_to :event
...
end
当我运行下面的代码片段时,它显示了 36 个查询:
@events = Event.where("date = ?", @date).all
@events.each do |e|
first = e.event_rows.first
first.event
end
当我运行这个片段时,我只得到 19 个查询
@events = Event.where("date = ?", @date).all
@events.each do |e|
first = e.event_rows.first
first.event = e # forcing the parent
first.event
end
我做错了什么,或者每次 EventRow 要求它的事件时,rails 都会运行一个查询?
回应评论:查询未标记为缓存:
SQL (0.7ms)[0m SELECT "event_rows"."id" AS t0_r0, "event_rows"."event_id" ... WHERE "event_rows"."event_id" = 1 LIMIT 1
Event Load (0.6ms)[0m [1mSELECT "events".* FROM "events" WHERE "events"."id" = 1 LIMIT 1[0m
SQL (3.2ms)[0m SELECT "event_rows"."id" AS t0_r0, "event_rows"."event_id" ... WHERE "event_rows"."event_id" = 2 LIMIT 1
Event Load (0.5ms)[0m [1mSELECT "events".* FROM "events" WHERE "events"."id" = 2 LIMIT 1[0m