Question

I am following Ryan Bate's Multitenancy with Scopes tutorial (http://railscasts.com/episodes/388-multitenancy-with-scopes) and I ran into the following error when I attempted to scope my users to the correct tenant:

undefined method users for #<Tenant:0x007fc61f075228>

The error references my show action in my users_controller.rb:

def show
  @user = current_tenant.users
end

This occurred because I removed the relationship in Tenants.rb to add cattr_accessor :current_id

class Tenant < ActiveRecord::Base
  cattr_accessor :current_id
  #has_many :users

  def self.current_id=(id)
    Thread.current[:tenant_id] = id
  end

  def self.current_id
    Thread.current[:tenant_id]
  end
end

In my user.rb, I added the default_scope:

class User < ActiveRecord::Base
  devise :database_authenticatable, :registerable,
     :recoverable, :rememberable, :trackable, :validatable

  default_scope { where(tenant_id: Tenant.current_id) }
end

Here is my applications_controller.rb:

class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  protect_from_forgery with: :exception

  around_filter :scope_current_tenant

  def after_sign_in_path_for(resource_or_scope)
    user_show_path(current_user.id)
  end

  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
end

I am not sure why Ryan removed the has_many :users relationship, but I assume it is to prevent users with different tenants to view each other.

How do I handle and fix this error?

Was it helpful?

Solution

It seem like you do not need use current_tenant.users

It scoped request to db automatic (uses default scope in user model).

Just

@users = Users.all

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top