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.
07752bc66e807b599e802595f0fdba13?d=identicon&s=25 Emmanuel Oga (Guest)
on 2007-06-13 19: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!
525128e48ca2b4c7fb6176ea166fccfd?d=identicon&s=25 Eric G. (gotskill10)
on 2007-06-13 20: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 Oga 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!
07752bc66e807b599e802595f0fdba13?d=identicon&s=25 Emmanuel Oga (Guest)
on 2007-06-13 21:33
Aryk Grosz 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 :(
72f8ab180f81f9c544e2b58da399c0be?d=identicon&s=25 Elad Meidar (eizesus)
on 2007-06-14 01: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 Oga <rails-mailing-l...@andreas-s.net>
This topic is locked and can not be replied to.