开发者

Is there a more efficient way to create an ActiveRecord relationship on a class that references itself through another table?

I apologize if the question title is confusing. I have the following situation: I have a Person model which stores people in the standard way in the people table.

I need to add a has_many relationship for emergency_contacts on the Person model. I tried doing this in the following way:

Migrations:

create_table :people do |t|
  t.string :first
  t.string :middle
  t.string :last

  t.timestamps
end
create_table :emergency_contacts, :id => false do |t|
  t.integer :person_id
  t.integer :emergency_contact_id

  t.timestamps
e开发者_Python百科nd

Models:

class Person < ActiveRecord::Base
  has_many :emergency_contacts

  validates :first, :presence => true
  validates :last, :presence => true
end
class EmergencyContact < ActiveRecord::Base
  belongs_to :person
  has_one :person, :foreign_key => 'emergency_contact_id'
end

This allows me to do:

ruby-1.9.2-p180 :001 > p = Person.new(first: "John", last: "Doe")
 => #<Person id: nil, first: "John", middle: nil, last: "Doe", created_at: nil, updated_at: nil> 
ruby-1.9.2-p180 :002 > ec = EmergencyContact.new
 => #<EmergencyContact person_id: nil, emergency_contact_id: nil, created_at: nil, updated_at: nil> 
ruby-1.9.2-p180 :003 > ec.emergency_contact = Person.new(first: "Peter", last: "Griffin")
 => #<Person id: nil, first: "Peter", middle: nil, last: "Griffin", created_at: nil, updated_at: nil> 
ruby-1.9.2-p180 :004 > p.emergency_contacts << ec
 => [#<EmergencyContact person_id: nil, emergency_contact_id: nil, created_at: nil, updated_at: nil>] 
ruby-1.9.2-p180 :005 > p.save!
 => true 

However, I don't feel the EmergencyContact model should have to be there, since I am really just referencing a Person model anyway.

Is there a way to remove this "middle-man" model, so that I can just do something like:

p = Person.new(first: "John", last: "Doe")
p.emergency_contacts << Person.new(first: "Peter", last: "Griffin")


I'd really use self referential associations for this kind of purpose.

Se tutorial here: http://railscasts.com/episodes/163-self-referential-association

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜