简体   繁体   中英

In Ruby on Rails, how do I create a table/model that has a field in it that references the same table?

I am trying to do this in Rails 3. I create a table (syntax on code examples may not be exactly right, I am trying to recreate from memory):

create_table "persons", :force => true do |t|
    t.string "name"
    t.integer "guest_of_id"
end

And I want guest_id to reference another row in the persons table. Each person is the guest of only one person. So in the model I set up the association:

class Person < ActiveRecord::Base
    belongs_to :GuestOf, :class => "Person", :foreign_key => "guest_of_id"
end

However, when I try to reference the guestOf field

a_person.GuestOf.name

I get the error

undefined method 'eq' for nil:NilClass

Is this possible in Rails? Am I doing something wrong? Am I missing a has_many relationship? I strongly suspect my Google-Fu is failing me. The only possible solution I have found is http://railscasts.com/episodes/163-self-referential-association but he is establishing a many to many relationship and I think it is more complicated than what I am trying to do.

Thanks.

You really should be able to just do:

class Person < ActiveRecord::Base
    belongs_to :host, :class => "Person", :foreign_key => "guest_of_id"
    has_one :guest, :class => "Person", :foreign_key => "guest_of_id"
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM