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
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With