开发者

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

开发者 https://www.devze.com 2023-02-06 10:54 出处:网络
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):

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
0

精彩评论

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