Rails 3 devise, current_user is not accessible in a Model?-Collection of common programming errors
Ryan Bates lays out a pretty safe way to implement this kind of strategy in this railscast
This a paid episode (don’t down vote me!) but you can browse the source code for free
Here he creates a current_tenant
method, but you could easily substitute current_user
instead.
Here are the key bits of code…
#application_controller.rb
around_filter :scope_current_tenant
private
def current_tenant
Tenant.find_by_subdomain! request.subdomain
end
helper_method :current_tenant
def scope_current_tenant
Tenant.current_id = current_tenant.id
yield
ensure
Tenant.current_id = nil
end
#models/tenant.rb
def self.current_id=(id)
Thread.current[:tenant_id] = id
end
def self.current_id
Thread.current[:tenant_id]
end
Then in the model you can do something like…
default_scope { where(tenant_id: Tenant.current_id) }