Rails 中急切加载的问题

发布于 2024-11-01 09:58:43 字数 676 浏览 0 评论 0原文

我在急于加载相关记录时遇到一些奇怪的行为。我已经在“包含”中指定了所需的关系,并且所有内容都通过四个查询加载。但是,当我迭代选定的记录时,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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

两人的回忆 2024-11-08 09:58:43

我相信这是因为 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 a scope on a model.

I suspect if you add .all to the end it will load the records in one query.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文