Search code examples
ruby-on-railsactiverecordassociationsbelongs-to

In Rails: how do I create a many-to-many relationship where both models have teh join key?


I have models A and B. Both have the magic column. If a record a from A and a b from B have the same magic, then they are related. Many records from A and B may have the same magic.

Is there a way to express this belongs_to_many sort of thing in my Rails models? How?


Solution

  • There's a high value in following the Rails way, and what you're trying to do isn't the standard way of doing this.

    The Rails Way: You should create a has-and-belongs-to-many relationship using an intermediate model and table, as described in the Rails Guides website.

    But if you insist...: Try this:

    # model_a.rb
    class ModelA < ActiveRecord::Base
      has_many :model_bs, class_name: 'ModelB',
                          foreign_key: :magic,
                          primary_key: :magic
    end
    
    # model_b.rb
    class ModelB < ActiveRecord::Base
      has_many :model_as, class_name: 'ModelA',
                          foreign_key: :magic,
                          primary_key: :magic
    end
    

    I haven't tested this, but I am fairly certain that it would work.

    Final words... Don't do it! Follow the Rails way. :)