Tim Scott
Tim Scott

Reputation: 15205

If Not With Named Scopes Then How?

I recently discovered scopes (me == Rails noob). Cool. But named scopes are dead I find out. I wanna do it right, so I change this:

 def Foo
    scope :only_some, where('some conditions')

To this (as directed):

class << self

   def only_some
      where('some conditions')
   end

end

And then this stopped working:

bar.foos.only_some

Exception:

undefined method `only_some' for #<ActiveRecord::Relation:0x007fb398d99178>

What am I doing wrong? Should I keep using scopes?

Upvotes: 2

Views: 384

Answers (1)

Salil
Salil

Reputation: 9722

On the contrary, scopes are preferred over class methods for querying associated objects because of two reasons:

  1. scopes simplify generation of complex queries. Think of scopes as 'lazy' sequences which get evaluated only when the caller needs the value (that is, in the end). So, you can construct a complex query by chaining scope methods without worrying about performance hit by multiple SQL queries. You can do so in class methods as well, but with less flexibility. You will have to use 'scoped' method in these class methods to act on the current scope.

  2. You can call scope methods on a collection of associated objects as well as on a single object. This is because ActiveRecord associations are instances of ActiveRecord::Relation class on which scope methods can be invoked whereas it is not the case with class methods. And this is precisely the problem you are facing. In your example, when you define 'only_some' as a scope method, ActiveRecord will invoke 'only_some' on ActiveRecord::Relation object which in turn will invoke that method on each of the foos. But when you redefine it to be a class method, you can call this method only on the model class Foo.

Upvotes: 2

Related Questions