I\'m writing a mentorship program for our church in rails (im still farily new to rails)..
And i need to model this..
contact
has_one :father, :class
I totally agree with zetetic. The question looks far more simpler then the answer and there is little we could do about it. I'll add my 20c though.
Tables:
create_table :contacts do |t|
t.string :name
t.string :gender
end
create_table :relations, :id => false do |t|
t.integer :parent_id
t.integer :child_id
end
Table relations does not have corresponding model.
class Contact < ActiveRecord::Base
has_and_belongs_to_many :parents,
:class_name => 'Contact',
:join_table => 'relations',
:foreign_key => 'child_id',
:association_foreign_key => 'parent_id'
has_and_belongs_to_many :children,
:class_name => 'Contact',
:join_table => 'relations',
:foreign_key => 'parent_id',
:association_foreign_key => 'child_id'
def siblings
result = self.parents.reduce [] {|children, p| children.concat p.children}
result.uniq.reject {|c| c == self}
end
def father
parents.where(:gender => 'm').first
end
def mother
parents.where(:gender => 'f').first
end
end
Now we have regular Rails assosiations. So we can
alice.parents << bob
alice.save
bob.chidren << cindy
bob.save
alice.parents.create(Contact.create(:name => 'Teresa', :gender => 'f')
and all stuff like that.