Search code examples
ruby-on-railsnaming-conventionsassociationshas-manytablename

rails n:m how to have rails associations when the db table names are different


I have a project which does not follow the rails nameing conventions, because it is not possible for a special case.

Scenario: I have a model called Foo, and the database table for this model called example_foos. I have a model called Bar, and the database table for this model called example_bars.

I want to create a n:m association between these two models with a model FooBar. Database table name for this model is ExampleFooExampleBars.

Now my question..how can I specify the has_many throught association in the models? If I do it like normal, I get errors because the model and table names are different..


Solution

  • The associations are referring to the class names, so:

    class Foo < ActiveRecord::Base
      set_table_name 'example_foos'
      has_many :bars
    end
    
    class Bar < ActiveRecord::Base
      set_table_name 'example_bars'
      belongs_to :foo
    end