How to override naming conventions in ROR

It is easy to override the naming conventions in ROR, which specify how the model class and database should be named.

The ApplicationRecord class, which defines multiple helpful methods, is inherited from ApplicationRecord::Base, which enables overriding the standard naming conventions. We can easily specify the name of the table by using ActiveRecord::Base.table_name= and setting as the name as we please.

class Vehicle < ApplicationRecord
self.table_name = "sedan"
end

If we opt for this method, we have to manually define the class name that is hosting the fixtures (sedan.yml). We can do this by including the method of set_fixture_class in the test definition.

class VehicleTest < ActiveSupport::TestCase
set_fixture_class model: Vehicle
fixtures :sedan
# ...
end

We can also override the column that is used as the primary key of a table with the help of the ActiveRecord::Base.primary_key= method.

class Vehicle < ApplicationRecord
self.primary_key = "registrationNumber"
end

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved