[英]Does Rails :delegate method always load the association?
I'm using the :delegate method in Rails 3.2 to get/set methods on an object's association. 我在Rails 3.2中使用:delegate方法获取/设置对象关联的方法。 This seems to always load the association, even when I'm not calling the delegated methods.
即使我没有调用委托的方法,这似乎总是会加载关联。
For instance, if I've got: 例如,如果我有:
class Post < ActiveRecord::Base
delegate :name, :to => :author, :prefix => true
end
If I do Post.all.limit(10)
ActiveRecord also loads the author for each of those posts, regardless of whether I'm ever accessing @post.author_name
. 如果我这样做,则
Post.all.limit(10)
不管我是否访问@post.author_name
,ActiveRecord也会为每个帖子加载作者。
Is there a way to load delegated associations lazily? 有没有一种方法可以延迟加载委托的关联? Or am I better off writing custom wrapper methods, which will load associations lazily?
还是我最好编写自定义包装方法,这些方法会延迟加载关联?
They don't eager-load for me, could it be something else in your code? 他们不急于为我加载,这可能是您代码中的其他内容吗?
In any case I've never liked using delegate
with prefix
, it seems kind of odd. 无论如何,我从未喜欢过使用带有
prefix
delegate
,这似乎有点奇怪。 You're no longer actually delegating a method, you've just defined a new method in a difficult to read and parse way. 您实际上不再委托一个方法,而是以一种难以阅读和解析的方式定义了一个新方法。 I'd just write a wrapper method as you suggested.
我只是按照您的建议编写包装器方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.