ruby-on-railsactiverecordnamed-scope

Can I use an ActiveRecord scope as an instance method?


I have a scope that acts as a filter. For instance:

class User
  scope :in_good_standing, -> { where(:some_val => 'foo', :some_other_val => 'bar' }
end

Because in_good_standing depends on more than one condition, I'd like to have this defined on an instance of User as:

def in_good_standing?
  some_val == 'foo' && some_other_val == 'bar'
end

However, I'd really like to avoid duplicating the logic between both the instance method and the named scope. Is there a way to define #in_good_standing? in a way that simply refers to the scope?

edit

I realize these are very different concepts (one is a class method, one is an instance method), hence my question. As @MrDanA mentioned in a comment, the closest I can get is to check whether or not the record I'm curious about exists within the larger scope, which is probably the answer I'm looking for.

The responses about separating out different scopes from my example are useful, but I'm looking for a general pattern to apply to an application with some very complicated logic being driven by scopes.


Solution

  • Adding my original comment as an answer:

    As @meagar stated, you can't, because they are doing very different things. The most you could do is have your instance method call the scope and check to see if it's part of the returned results. However that won't work if the instance has not been saved yet. So in your method you could do:

    User.in_good_standing.where(:id => self.id).present?