The noteworthy things about it are that its habtm associations are
self-referential and that two of them have conditions. Let’s see how to
use this. Also, the brothers and sisters associations use different
ways to refer to the column on which their respective condition
depends.
Lets put this class through its paces.
Person.find(:first, :include => :sisters)
→ works
Person.find(:first, :include => :brothers)
→ exception; invalid SQL, reference to column ‘gender’ is ambiguous
p = Person.find(:first)
p.brothers.map(&:first_name)
→ works
p.sisters.map(&:first_name)
→ exception; invalid SQL, no alias defined for sisters_people
I may be missing something, but from what it looks like, ActiveRecord
doesn’t handle this case as it should.
class Person < ActiveRecord::Base
has_and_belongs_to_many :relatives,
:class_name => ‘Person’, :join_table => ‘relatives’,
:foreign_key => ‘from_id’, :association_foreign_key => ‘to_id’
Michael
Could you please provide the schema that this code is running against.
As a guess, it looks as though gender is defined in both the People?
table and it’s join (Relatives?) which would lead to an ambiguous query
unless it was explicitly qualified as it was in the sister’s case.
The noteworthy things about it are that its habtm associations are
self-referential and that two of them have conditions. Let’s see how to
use this. Also, the brothers and sisters associations use different
ways to refer to the column on which their respective condition
depends.
Hi Michael
that’s exactly what I am trying to solve using a :through statement…
if you solve this problem, please let me know… I’ll appreciate cloning
your definitions…
Could you please provide the schema that this code is running
against. As a guess, it looks as though gender is defined in both the
People? table and it’s join (Relatives?) which would lead to an
ambiguous query unless it was explicitly qualified as it was in the
sister’s case.
create_table “relatives”, :id => false, :force => true do |t|
t.column “from_id”, :integer, :null => false
t.column “to_id”, :integer, :null => false
end
end
In case it wasn’t clear from my original message, the point I’m trying
to make is that apparently it is not possible to specify a condition on
a habtm association in such a way that both fetching the associated
objects and finding with the association :include’d are possible.