Here’s the basic situation
class Person < ActiveRecord::Base
acts_as_tree
belongs_to :hair_color
validates_presence_of :name
end
class HairColor < ActiveRecord::Base
validates_presence_of :name
end
What I want to achieve:
I need another association on Person that returns only the red-haired
children. In my special case[*] it has to be an association, an
association extension, named scope or similar won’t do. In particular,
this association has to work when listing all persons and their
red-headed children and possibly with a filter condition.
A first stab looks like this
class Person < ActiveRecord::Base
…
has_many :redheads, :class_name => ‘Person’,
:foreign_key => :parent_id,
:include => :hair_color,
:conditions => “hair_colors.name = ‘red’”
end
This works indeed for a case like this
p = Person.find(:first)
p.redheads
however, it doesn’t work for
parents = Person.find(:all, :include => :redheads)
In that case, the secondary assocation (redheads.hair_color) doesn’t
even seem to be included. Adding it manually like this
parents = Person.find(:all, :include => [:redheads, :hair_color])
doesn’t help because the “scoping” is wrong: hair_color is joined on the
parents, not the children.
So, is there a way to make ActiveRecord do what I need without resorting
to hand-written SQL?
Michael
[*] I already have the infrastructure to display and filter lists of
objects with associated objects one-level deep. E.g., for a list of
persons I could define a column { :column => ‘hair_color.name’, :title
=> ‘Hair color’ }. I’d like to specify a column such as { :column
=> ‘redheads.name’, :title => ‘Redheads’ }.
–
Michael S.
mailto:[email protected]
http://www.schuerig.de/michael/