Always eager load

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

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?


This seems to work:

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

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


If there’s already an options[:include] you’re going to use it then,
[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
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


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 forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs