【问题标题】:Does :include work on ActiveRecord instances?:include 是否适用于 ActiveRecord 实例?
【发布时间】:2011-05-08 20:45:39
【问题描述】:

所有用于急切加载的 :include 示例都是用于类级别的查询。我在我的模型实例上尝试了它,但它仍然发出一堆查询 - 它是否适用于实例方法?

 #in controller
 @emails = person.sent_emails(:include => [:recipient])

 #in view
 render @emails

 # _email.html.erb partial
 <h1><%= email.recipient.name %></h1>
 <p>
 <%= email.content %>
 </p>

 #still issues a select * for emails, N+1 for recipients :/

【问题讨论】:

  • 部分_email里面是什么?
  • 已将其添加到问题中
  • 如果收件人没有急切加载,email.recipient 调用应该运行 select * from users。你确定你看到select * from emails 多次吗?
  • select * from emails 发生一次,然后 select * from people where id = :recipient_id N 次

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


【解决方案1】:

我知道它看起来有点 Rails 2ish,可能有更好的 Rails 3 方式,但这确实有效。

@emails = person.sent_emails.find(:all, :include => :recipient)

编辑:请参阅 BaroqueBobcat 的评论,了解 Rails 3 中的更好方法

【讨论】:

  • 你可以使用sent_emails.all(:include =&gt; :recipient)
  • 使用了 BaroqueBobcat 的语法——这就是我所缺少的。谢谢
  • 好的,所以在这个例子中我有一个 Person 实例。我可以做“person.sent_emails.all(:include => :recipient)”。它返回我预期的结果。但是 person.sent_emails 变量没有改变。如何在 ActiveRecord 实例中加载这些关联?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-24
  • 2011-06-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多