Setting table name in namespace model
-
04-07-2021 - |
Question
I have some namespaced models which I'm trying to override the default rails table name for them because I'm connecting to an existing legacy database.
My models are:
/app/models/licenses.rb
module Licenses
def self.table_name_prefix
''
end
end
/app/models/licenses/employee.rb
class Licenses::Employee < ActiveRecord::Base
establish_connection YAML::load(File.open("#{Rails.root}/config/licenses_database.yml"))[Rails.env]
self.table_name = 'EMPLOYEE'
self.primary_key = 'EMPLOYEE_ID'
end
/app/models/licenses/inspection.rb
class Licenses::Inspection < ActiveRecord::Base
establish_connection YAML::load(File.open("#{Rails.root}/config/licenses_database.yml"))[Rails.env]
self.table_name = 'INSPECTION'
self.primary_key = 'INSPECTION_ID'
end
When I run my tests, errors are generated as the
PG::Error: ERROR: relation "licenses_employees" does not exist
Is there something I'm missing to remove the prefix from the namespaced models?
UPDATE: I've tried setting the table name prefix in the Licenses module to 'testing_' instead of '' and I still get the same error message.
Solution
It appears that the issue at hand was that I used the rails generator to create the namespace models for the existing database. The generator had created the fixture files as namespaced fixtures i.e. /test/fixtures/licenses/employees.yml
. When I tried to run my tests, Rails would try to insert the fixtures into the tables based on the fixture name/path. I just needed to move the fixture files for the existing database and rename them to match the table name that I set in the models i.e. /test/fixtures/licenses/employee.yml
.