Forum: Ruby on Rails Has and belongs to many with a single table

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Emmanuel O. (Guest)
on 2007-06-13 21:39
Is it posible to implement "Has and belongs to many" with a single
table?

Like this:

>>table events
  id: integer
  description: text

>>table related_events
  id_event: integer
  id_related_event: integer

class Event < ActiveRecord::Base

  # How can i add a has and belong to many reference to self?

end


Thank you!
Eric G. (Guest)
on 2007-06-13 22:17
I would recommend doing a has_many :through back to itself. Just make
sure you do call the event table two different things like:

class RelatedEvents
   belongs_to :first_event
   belongs_to :second_event
end




Emmanuel O. wrote:
> Is it posible to implement "Has and belongs to many" with a single
> table?
>
> Like this:
>
>>>table events
>   id: integer
>   description: text
>
>>>table related_events
>   id_event: integer
>   id_related_event: integer
>
> class Event < ActiveRecord::Base
>
>   # How can i add a has and belong to many reference to self?
>
> end
>
>
> Thank you!
Emmanuel O. (Guest)
on 2007-06-13 23:33
Aryk G. wrote:
> I would recommend doing a has_many :through back to itself. Just make
> sure you do call the event table two different things like:
>
> class RelatedEvents
>    belongs_to :first_event
>    belongs_to :second_event
> end
>
>
>

Mmmmm i don't quite get the idea :(
Elad M. (Guest)
on 2007-06-14 03:14
(Received via mailing list)
It's pretty simple, all you need to do is to create 2 foreign keys and
specify to where they point to.

class Event << ActiveRecord::Base

  belongs_to :first_event, :class_name => "Event", :foreign_key =>
"first_event_id"
  belongs_to :second_event, :class_name => "Event", :foreign_key =>
"second_event_id"

end



On Jun 13, 3:33 pm, Emmanuel O. <removed_email_address@domain.invalid>
This topic is locked and can not be replied to.