Rails 中急切加载的问题
我在急于加载相关记录时遇到一些奇怪的行为。我已经在“包含”中指定了所需的关系,并且所有内容都通过四个查询加载。但是,当我迭代选定的记录时,Rails 开始对每个相关实体发出查询,大部分时间都会访问缓存。我无法在具有类似设置的测试应用程序中重现此问题。以下是代码的相关部分:
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}
连接用于稍后添加谓词。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我相信这是因为 Rails 的“延迟加载”方式 - 因此,在调用
Side.includes(...).limit(50)
时,您实际上并没有请求任何记录。可以将其视为在模型上设置范围
。我怀疑如果您将
.all
添加到末尾,它将在一个查询中加载记录。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 ascope
on a model.I suspect if you add
.all
to the end it will load the records in one query.