2

Can anyone tell me about scopes? I have gone through the rails guide but still want to know how exactly it works?

notapatch
  • 6,569
  • 6
  • 41
  • 45
aakashshukla
  • 25
  • 1
  • 3

1 Answers1

11

Scope adds a class method for retrieving and querying objects.

Consider one simple example You have one table named shirts with column color and so many. Now if you want the shirts with red color then you can simply do like this in Shirt model

class Shirt < ActiveRecord::Base
  scope :red_shirts, -> { where(color: red) }
end

Now this allows you to access red shirts by simply doing this:

Shirt.red_shirts.each do 
  #do_something
end

You could use class method also but it takes a little bit of extra work. Scopes prefer to return scopes, so they’re easy to chain together.

Swapnil Patil
  • 912
  • 1
  • 7
  • 14