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
精彩评论