nomad
nomad

Reputation: 65

Creating a Users list that is personalized by subdomain Rails

I currently have a system that allows a user who has created an account to invite additional users to their team. Unfortunately When viewing the user list it displays ALL users from every team. I want this list to be separated by subdomain and partitioned by each team. I have a projects controller which is partitioned like this by using a current_account method.

application_controller.rb

def current_account
  @current_account ||= User.find_by(subdomain: request.subdomain)
end

projects_controller.rb

def index
  @project = current_account.projects
end

invites_controller.rb

def index
  @user = current_account.users      
end

When I navigate to the index action route url of the invites_controller I received the following error:

NoMethodError in Users::InvitesController#index
undefined method `users' for

However when I navigate to the index action route url of the projects_controller everything works as expected. Why can't I use the current_account method in the invites_controller, just like I did with the projects_controller?

Upvotes: 0

Views: 70

Answers (1)

MZaragoza
MZaragoza

Reputation: 10111

I have done this many times.

What I do is like you I have a current_account method in the application controller

#app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
  ...
  def current_account
    @current_account ||= User.find_by(subdomain: request.subdomain)
  end
  ...
end

the key is that each user also has a account_id or you have a way to have a user to accounts table

I have a account_id in my users

class AddAccountIdToUsers < ActiveRecord::Migration[5.0]
  def change
    add_column :users, :account_id, :integer
  end
end

Now you need to remember to add the association of account has many users and user belongs to a account

Models

#app/models/account.rb
class Account < ApplicationRecord
  has_many :users
  ...
end

#app/models/user.rb
class User < ApplicationRecord
  belongs_to :account
  ...
end

now in your controller you can do

@users = current_account.useres

Upvotes: 1

Related Questions