1

I have a model named Course.each course has two kind of many-to-many relation with other courses. so I need two join tables. how can i implement it in rails?

MDK
  • 680
  • 1
  • 9
  • 20

1 Answers1

4

See the following (looong) answer for a pretty comprehensive list of possible ways to do HABTM associations between objects of the same model: https://stackoverflow.com/a/2168528/454094

Once you decide on whether to use a "normal" join table or use the :through option with a model inbetween, defining two different HABTM associations shouldn't be more complicated than using different names and join tables / models for them. E.g.

class Person < ActiveRecord::Base

  has_and_belongs_to_many(:friends,
    class_name: "Person",
    join_table: "friend_connections",
    foreign_key: "person_a_id",
    association_foreign_key: "person_b_id")

  has_and_belongs_to_many(:foes,
    class_name: "Person",
    join_table: "foes_connections",
    foreign_key: "person_a_id",
    association_foreign_key: "person_b_id")

end

Note: as the linked answer states, the above associations will be one-way. E.g. bob.friends << alice will not automatically make bob appear in alice.friends. Depending on your particular project, that may or may not be a dealbreaker. Still, hope this helped.

Community
  • 1
  • 1
lime
  • 6,901
  • 4
  • 39
  • 50