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

341 Views Asked by At

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..

2

There are 2 best solutions below

0
On BEST ANSWER

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
0
On

If your model and table has different name you can

class Foo <ActiveRecord::Base
  set_table_name "example_foos"
end

rest of association as per rails convention way