Mark Locklear
Mark Locklear

Reputation: 5325

What is appropriate scope to replace this method?

I have a dashboard_controller that I am using to manage users. Here is that controller:

class DashboardController < ApplicationController
  before_action :authenticate_user!

  def index
    if current_user.admin?
      @users = current_user.get_organization_users
    else

    flash[:notice] = "Unauthorized Page View"
    redirect_to(tasks_url)
  end
end

Note I am using @users = current_user.get_organization_users. Here is the get_organization_users method in my user model...

def get_organization_users
  self.organization.users
end

How would I replace this with a scope? I tried...

scope :organization_users, -> { self.organization.users }

...but no worky. Any help appreciated.

Upvotes: 1

Views: 44

Answers (3)

Arun Kumar Mohan
Arun Kumar Mohan

Reputation: 11905

A scope is used to add a class method to your model. But you're trying to call the method on an instance. So, in this case, the instance method makes sense.

However, if you want to create a scope, pass in the user_id as a parameter to the scope.

scope :organization_users(user_id), -> { find(user_id).organization.users }

Upvotes: 1

Maciej Małecki
Maciej Małecki

Reputation: 2745

I am not sure about your question. You want to fetch all users that belongs to the organization associated with the current user, right? In such case you should just call current_user.organization.users.

Scope is used for filtering records in the current model and not for getting objects that are in the relation. You can read about it in the official documentation: http://guides.rubyonrails.org/active_record_querying.html#scopes.

Upvotes: 0

Cent
Cent

Reputation: 881

Internally, Active record converts scopes into class methods.

That would mean that you can't replace the instance method get_organization_users with a scope and expect to call it on current_user, an instance of the class.

What you could do is create a scope and pass an argument (most probably the user id) to it, then call that scope directly on the user class.

I could give an example if you wish, but I think this approach is much longer than the desired one.

Upvotes: 1

Related Questions