Model Scopes in Rails 3

A scope is a subset of a collection. The first and most obvious benefit related to scopes is that everything is scoped! That means you no longer have to use find(…) on an ActiveRecord model/controller and have a query immediately be executed[When we are writing any find method in controller action, will immediate execute when action called, If case would be, we have such a five find method and each executing over million of data. It would cause performance issues ]. We can actually build queries up and only execute them when we use them(from view/controller/helper).

More important, Scopes are chainable. This has two principal benefits: first, we can programmatically generate complex queries (based on user input or other data); and second, we can refactor your queries to eliminate code duplication in a way that we never could before. For me it’s easily been one of the most beneficial features in helping to keep my code ‘DRY’.

We can use every method such as where, joins and includes. All scope methods will return an ActiveRecord::Relation object which will allow for further methods (such as other scopes) to be called on it.

scope :social_n_parents, where(:social_type.exists => true).and(:challenge_id.exists => false)
scope :recently_created, desc(:created_at)

we call this scope like this.


We can also pass in variables to named scopes by using a lambda…

class Challenge < ActiveRecord::Base
named_scope :by_invitee, lambda { |invitee| { :conditions => [“invitee_id = ?”,] }}

@your_guest = Challenge.by_invitee(current_user)

That’s it. Cheers…!!!!!!!!!!!!!

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s