I'm working on a legacy code base in Rails 5.0 where there isn't really the resources for upgrading to a newer version. That said, I'm trying to understand whether or not this solution would be thread safe and if not, what can be done to improve it. I have an Organization model and many other models tied to this one but for simplicity, I'll stick with the User model.
class Organization < ApplicationRecord
has_many :users, dependent: :destroy
def self.current_id=(id)
Thread.current[:organization_id] = id
end
def self.current_id
Thread.current[:organization_id]
end
validates_uniqueness_of :name, presence: true
end
class User < ApplicationRecord
devise :database_authenticatable,
:rememberable, :trackable,
:registerable
belongs_to :organization
default_scope { where(organization_id: Organization.current_id)}
end
This is my application controller
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
# get the organization from the domain before
prepend_around_filter :scope_current_organization
private
def require_active_user!
raise "Called ApplicationController#require_active_user! without user" unless user_signed_in?
if !current_user.active?
redirect_to inactive_account_path
end
end
def current_organization
Organization.find_by!(subdomain: request.subdomain)
end
helper_method :current_tenant
def scope_current_organization
Organization.current_id = current_organization.id
yield
ensure
Organization.current_id = nil
end
end
From my local development testing this solution seems to work but I'm wondering what aspects of thread safety I may have missed. Thanks in advance for your help!
From my local development testing this solution seems to work but I'm wondering what aspects of thread safety I may have missed. Thanks in advance for your help!