Rails many-to-many same class bi-directional relationship.. how?
So heres the deal.. i'm writing a rails application to manage contact data..
I have a contact model and that contact needs to have many family members (still the contact class).. that relationship needs associated relationship data.. ie
ContactA | ContactB | Relationship
1 2 Contact A is Contact B's Father
How can i relate 2 objects of the same class and attach some data and be able to traverse te relationship bidirectionally like so:
@guy1 = Contact.find(1) #Guy A
@guy1.family_relationships
>开发者_开发问答>> [[guyb, "f"], [guyc, "s"]]
@guy2 = @guy1.family_members.first
@guy1.family_members
>>> [[guya]]
Thats probably not 100% correct but its late and ive been battling with a server all day so please forgive me!!
I've heard you have to do all kinds of hacky SQL to do it..
Thanks!
Daniel
I had a similar situation in one of my projects earlier. I went with the following design:
class Patient < AR::Base
has_many :relatives, :dependent => :destroy do
def husband
select { |r| r.relation.eql?('Husband').first
end
def father
select { |r| r.relation.eql?('Father').first
end
...
def sons
select { |r| r.relation.eql?('Son')
end
...
end
end
class Relative < AR::Base
belongs_to :patient
validates :relation,
:inclusion => {
:in => %w( Husband Daughter Son Father Mother Brother Sister )
}
end
This works for me. Hope this helps you or at least point you in the right direction!
Thanks for the great answers but found the answer here:
http://railscasts.com/episodes/163-self-referential-association
Railscasts is awesome!
精彩评论