简体   繁体   中英

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. 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 .

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM