Realization of several tenants in rails

We have a mid-sized application deployed for several clients on their respective VPS online servers. The code is the same for all customers. Maintenance is becoming a huge burden. Even the same change, we deploy on many servers. Thus, we plan to introduce a multiple rental function for our application.

We encountered several gems, but this does not mean that we use this goal, and therefore we plan to realize it.

We created a new Client model, and we created an abstract superclass that inherits from ActiveRecord::Base , and all dependent classes inherit this class. Now the problem arises when I want to add default_scope from my superclass.

 class SuperClass < ActiveRecord::Base self.abstract_class = true default_scope where(:client_id => ???) end 

??? changes for each user. Therefore, I cannot give a static value. But I'm not sure how I can dynamically set this area. So what can be done?

+4
source share
1 answer

We do something like the following (you may not need the thread-safe part):

 class Client < ActiveRecord::Base def self.current Thread.current['current_client'] end def self.current=(client) Thread.current['current_client'] = client end end class SuperClass < ActiveRecord::Base self.abstract_class = true # Note that the default scope has to be in a lambda or block. That means it eval'd during each request. # Otherwise it would be eval'd at load time and wouldn't work as expected. default_scope { Client.current ? where(:client_id => Client.current.id ) : nil } end 

Then in the ApplicationController we add a filter before installing the current client based on the subdomain:

 class ApplicationController < ActionController::Base before_filter :set_current_client def set_current_client Client.current = Client.find_by_subdomain(request.subdomain) end end 
+5
source

Source: https://habr.com/ru/post/1439574/


All Articles