0

I'm using a Rails application to access a Dynamics NAV Database (today is called Dynamics 365 Business Central). In order to make it multi tenant, they partition the DB using table name prefixes ex: Company 1$Warehouse Entry or Company 2$Warehouse Entry.

I wanted to use a field defined in my User model in order to set the company name that it access.

In order to access the current user in the model I have used the following on application_controller.rb

before_action -> { User.current = current_user }

And then I set a base class where it declares the following instance method:

def self.set_company_name
  company = User.current.nav_company ? User.current.nav_company + "$" : "Company 1$"
  self.table_name = company + self.table_name
end

I also tried to use instance variables @@company but after reading I saw that table names in rails are cached.

What I have done works, but only if you restart the application. The table name doesn't change in runtime.

How can I make it dynamic? I saw this Question but the answer didn't show how to do this.

kaspermoerch
  • 16,127
  • 4
  • 44
  • 67
Rhuan
  • 135
  • 9
  • `Company 1$Warehouse Entry` and `Company 2$Warehouse Entry` are different tables? – asceta Jan 29 '21 at 21:32
  • Yes. Two different tables – Rhuan Jan 30 '21 at 22:07
  • ActiveRecord pattern pretends, at least in Ruby on Rails implementation, that every table on your database must be associate with only one model.There is a compelling reason to use the same user model class for two different tables? – asceta Mar 26 '21 at 17:29
  • Yes. they are the same model, just differs by the table name prefix. – Rhuan Jun 01 '21 at 15:03

1 Answers1

0

I don't know anything about Dynamics 365 and I don't understand why you want to associate two tables to one model, but I have worked with schemas/namespaces in postgresql for example: config.users where config is the schema and users the table name; so you can use it like select * from config.users.

Rails can easily adapt to this struct like you can see here.

asceta
  • 77
  • 2
  • 12
  • schema/namespaces is not what I'm looking for... The problem is that the change is on table name, not on schema. Maybe there's a way to avoid caching table names in Rails. – Rhuan Mar 26 '21 at 11:29