Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I call a named scope from within the model code where it was just defined?

This is my model and I'm trying to call self.red but it's not working. Is this even possible?

# Shirt has size and color
class Shirt < ActiveRecord::Base
    scope :red, where(:color => 'red')

    def find_red
        return self.red
    end
end
like image 939
Lan Avatar asked Jan 10 '11 01:01

Lan


People also ask

What is scope in Rails model?

Scopes are custom queries that you define inside your Rails models with the scope method. Every scope takes two arguments: A name, which you use to call this scope in your code. A lambda, which implements the query.

What is named scope in Ruby?

In Ruby on Rails, named scopes are similar to class methods (“class. method”) as opposed to instance methods (“class#method”). Named scopes are short code defined in a model and used to query Active Record database.

What is scope in ActiveRecord?

Scopes are used to assign complex ActiveRecord queries into customized methods using Ruby on Rails. Inside your models, you can define a scope as a new method that returns a lambda function for calling queries you're probably used to using inside your controllers.


2 Answers

Try Shirt.red
self.red would be an object method. scope :red is already a class method so you don't have to write a method find_red to perform a query, Shirt.red will already do that.

like image 91
fflyer05 Avatar answered Nov 11 '22 23:11

fflyer05


You might find calling self.class.red preferable to the Shirt.red proposed in the other answers. It isn't quite as nice to read, but it has the advantage that if the classes name every changes your code can remain the same.

like image 36
Noz Avatar answered Nov 11 '22 23:11

Noz