Default :include value for ActiveRecord::Base.find

Hi all,

I’m working on a application with lots of complicated data
relationships and thousands of rows of data. To speed up queries, I’m
using Project.find(:all, :conditions => some_hash, :include =>
some_other_hash). I’m using the same hash for :include quite a lot -
is there a way to specify in the Project model that it should use a
certain :include hash in find() by default so I can DRY up my code?

Thanks,
James

Hi

You can always define a class method for Project that wraps the find,
something like (warn absolutely untested)

class Project
def self.find_std_include(*args)
options = {:include => your_standard_include_hash}
if args.last.is_a? Hash
options.update(args.pop)
end
self.find(*args.push(options))
end
end

This way you can call Project.find_std_include() every time you need
to use the standard include clause.

Paolo

Thanks Paolo. I figured a class method was probably the way to go, but
was wondering if there was any way of modifying the default behaviour
of find() on a per-class basis. Thanks for the help.

Sure, there is a way.

class Project
class << self
alias find_without_standard_includes find
def find_with_standard_includes(*args)
options = {:include => your_standard_include_hash}
if args.last.is_a? Hash
options.update(args.pop)
end
self.find_without_standard_includes(*args.push(options))
end
alias find find_with_standard_includes
end
end

If you do not understand the class << self syntax: Every Method inside
class << self … end is considered a method of the self object, that
is the class itself in this context. This is needed, because alias does
only work with method names (alias self.find_without_standard_includes
self.find does not work).

Have fun
Florian

[email protected] wrote:

Thanks Paolo. I figured a class method was probably the way to go, but
was wondering if there was any way of modifying the default behaviour
of find() on a per-class basis. Thanks for the help.

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