In Ruby on Rails, how do I create a table/model that has a field in it that references the same table? -
i trying in rails 3. create table (syntax on code examples may not right, trying recreate memory):
create_table "persons", :force => true |t| t.string "name" t.integer "guest_of_id" end
and want guest_id reference row in persons table. each person guest of 1 person. in model set association:
class person < activerecord::base belongs_to :guestof, :class => "person", :foreign_key => "guest_of_id" end
however, when try reference guestof field
a_person.guestof.name
i error
undefined method 'eq' nil:nilclass
is possible in rails? doing wrong? missing has_many relationship? suspect google-fu failing me. possible solution have found http://railscasts.com/episodes/163-self-referential-association establishing many many relationship , think more complicated trying do.
thanks.
you should able 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
Comments
Post a Comment