On 8 April 2010 08:07, Joe <[email protected]> wrote:
> My schema looks like
>
>  create_table "people", :force => true do |t|
>    t.string   "name"
>    t.string   "sex"
>    t.integer  "father_id"
>    t.integer  "mother_id"
>  end
>
> and my model I want something like:
>
> class Person < ActiveRecord::Base
>  belongs_to :father, :class_name => "Person"
>  belongs_to :mother, :class_name => "Person"

What about children with two mums or two dads? Or the more frequent
occasion where there's a mum, dad and one or more step-parents? How
about children looked after by their grandparents?

You might be better off (and it would make your example query easier
too) if you removed the foreign keys from people, and had a
relationship like:

class Person < ActiveRecord::Base
 has_many :parents
end

create_table "parents" do |t|
   t.string   "relationship" # mother/father/stepmother/etc
   t.integer  "child_id"
   t.integer  "person_id"
end

class Parent < ActiveRecord::Base
 belongs_to :child, :class_name => "Person"
 belongs_to :person # this is the link for the "parent" person
end

If you *have* to only have one mother and father and nothing else, my
suggestion lets you do that by putting an index on parents across
relationship and child_id to ensure only one of each, and validate
that only mother/father is put into the relationship field.

Then, including a relationship like:
 has_many :children, :through => "parents", :class_name => "Person"

... gives you Person.first.children

-- 
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Talk" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-talk?hl=en.

Reply via email to