Troubles with eager loading in Rails
I'm experiencing some strange behavior while eager loading related records. I've specified needed relations in "includes" and 开发者_运维知识库all the stuff is loaded with four queries. But when I iterate over selected records, Rails starts issuing a query for each related entity, hitting the cache most of the time. I wasn't able to reproduce this problem in a test app with similar setup. Here are the relevant parts of the code:
class Side < ActiveRecord::Base
belongs_to :photo
belongs_to :board
end
class Board < ActiveRecord::Base
belongs_to :address
has_many :sides
end
class Photo < ActiveRecord::Base
has_many :sides
end
class Address < ActiveRecord::Base
belongs_to :city
has_many :boards
end
class City < ActiveRecord::Base
has_many :addresses
end
q = Side.includes({:board => :address}, :photo).joins({:board => :address}, :projects).limit(50)
q.each {|s| s.photo}
Joins are for predicates to be added later.
I believe this is because of the way rails is 'lazy loading' – So where you call Side.includes(...).limit(50)
you're not actually requesting any records. Think of it like setting up a scope
on a model.
I suspect if you add .all
to the end it will load the records in one query.
精彩评论