Using separate tables in Rails with model inheritance
Suppose there is a situation where you have two separate tables with the exact same structure, and you want to use separate models in Rails. Obviously, you want shared functionality from the models (order, scopes etc.), so the most logical way to go about it seems to be:
class Vehicle < ActiveRecord::Base
end
class Car < Vehicle
end
The problem however, is that is triggers Single Table Inheritance, even when you don’t have a type column in your table. So, in the example above Rails will always use the vehicles table. Luckily, there is a way to override Rails’s method of inferring the table name from the class name. It works like this:
class Vehicle < ActiveRecord::Base
end
class Car < Vehicle
set_table_name 'cars'
end
Now your models will behave as expected.
-
breyten posted this