Forum: Ruby on Rails Always eager load

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
(Guest)
on 2007-02-17 16:16
(Received via mailing list)
Is it possible to make a model always eager load an association,
without explicitly specifying it every time? For example:

class Article < AR::Base
  has_one :author
end

I'm *always* going to need the Author for the Article, so is there a
way to set :include => :author by default for find()? I thought about
overwriting find() on Article and then just call super() with
the :include, but I'm not exactly sure how that would go. Any ideas?

Thanks
(Guest)
on 2007-02-17 18:15
(Received via mailing list)
This seems to work:

def self.find(*args)
  options = extract_options_from_args!(args)
  options[:include] ||= :author
  super(args.first, options)
end

Is there an easier way or are there any problems with this approach?

Thanks
Russell N. (Guest)
on 2007-02-17 18:28
(Received via mailing list)
If there's already an options[:include] you're going to use it then,
right?
[That's what the code says.] If you're wanting to append it to any other
manual :include, you'll need to convert options[:include] to an array
and
all. If there's no other possible models to include then you could
options[:include] = :author instead. But I'd say you've got it solved
already.

RSL
(Guest)
on 2007-02-18 06:49
(Received via mailing list)
Actually, it's the opposite, if there is an :include defined then it
does nothing, this way I can specify :include => nil if I didn't want
to eager load (which won't happen, but just in case). That seems to do
the job then, thank you.
This topic is locked and can not be replied to.