:include 对 ActiveRecord 实例有效吗?
用于预加载的 :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 :/
All the examples of :include for eager loading are for class-level querying. I tried it on my model instance and it still issued a bunch of queries - does it work on instance methods?
#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 :/
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我知道它看起来有点像 Rails 2,可能有更好的 Rails 3 方式,但这确实有效。
编辑:请参阅 BaroqueBobcat 的评论,了解 Rails 3 中更好的方法
It looks a bit Rails 2ish I know and there may be a better Rails 3 way but this does work.
Edit: See the comment by BaroqueBobcat for a better method in Rails 3