ruby-on-railsrails-activerecord

Do I need to use Class.scope_name when using scope in the same model, or can I just use scope_name?


class User < ApplicationRecord
  scope :active, -> { where(active: true) }

  def some_method_in_user_model
    users = active # -> is this right or
    users = User.active # is this right?
    # additional code
  end
end

I think both are working but which one is better?


Solution

  • Both work but they do different things.

    A scope is, essentially, a class method. This:

    scope :active, -> { where(active: true) }
    

    is equivalent to:

    def self.active
      where(active: true)
    end
    

    and so users = User.active gives you all the active users in users as a query.

    You also have an active attribute in your model so this:

    users = active
    

    in an instance method works in the sense that it is syntactically valid and won't raise an exception. However, that will give you a boolean value (or possibly nil) in users and that's probably not what you're looking for and not what the variable name would imply.

    If you want to access the scope in an instance method, you'd want:

    def some_method
      users = User.active
      # or even `users = self.class.active`
    end
    

    If you want to access the scope in another class method, you'd want:

    def self.some_class_method
      users = active
      # or `users = User.active`
    end