【问题标题】:Rails ActiveRecord - eager loading (sort of) when using 'build' from has_manyRails ActiveRecord - 使用has_many的'build'时急切加载(有点)
【发布时间】:2009-12-08 19:38:08
【问题描述】:

我有一种情况,子级已构建但未保存,然后在视图中使用并引用父级。这导致了 Rails 记录缓存的广泛使用。我想让父母“渴望加载”未保存的子记录。

class Parent < ActiveRecord::Base
  has_many :children
  def make_children
    loop..
      children_array << children.build(...)
    end
  end
end

然后在视图中(注意'child'没有保存到DB):

children_array.each do |child|
  # What's the best way to optimise this so it doesn't
  # keep selecting parent albeit from the cache?
  child.parent 
end

【问题讨论】:

  • 注意:我在这里使用了术语预加载来表示我所追求的,尽管我知道在这种情况下预加载是不可能的,因为它不是从数据库中获取的,因此可以'不要像通常的急切加载那样使用连接。

标签: ruby-on-rails activerecord eager-loading


【解决方案1】:

我不确定我是否理解问题所在。查询缓存是你的朋友......!您对.parent 的调用没有访问数据库。

如果您可以提供有关您正在尝试做什么的更多信息,则可能会更容易帮助解决问题。

【讨论】:

  • 谢谢 jonnii - 你是对的......'查询缓存是你的朋友'。我有点跑题了,以为我会发布一个问题来阻止自己。那么查询缓存是否没有任何值得担心的重大开销?
  • 我不这么认为。这绝对比实际击中数据库要好。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-17
  • 2015-09-09
  • 1970-01-01
  • 2020-10-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多