«

»

Dec
20
2011

How to Create Named Scope in Rails

Named scope used to specify commonly used sql queries which can be define as method on model or on the association objects. With named scope, you can use every that have been included ActiveRecord method such us joins, select, where and etc.

Most of us start out writing our queries directly in the controllers, like this :

class  ArticleController < ApplicationController

  def article_today
    @articles = Article.where(["created_at > ?", Time.now.beginning_of_day])
  end
end

That’s works, but it’s broken cardinal role of Rails development. Rather than we embedding sql query in our controller to find article which created today in our site, much better to write something code called named scope in model which would return a collection of Article objects. To create a scope, we use the named_scope method in Rails 2 and scope method in Raials 3 above inside the class model.

Rails 2 :

class Article < ActiveRecord::Base

 named_scope :today, where(["created_at > ?", Time.now.beginning_of_day])
end

Rails 3 above :

class Article < ActiveRecord::Base

 scope :today, where(["created_at > ?", Time.now.beginning_of_day])
end

Then in our controller we call :

calss ArticlesController < ApplicationController
 def article_today
 @articles = Article.today
 end
end

That’s would return a collection of Article objects which created today. It’s look DRY query. In addition we also use scope to get object with join table. Please look below :

Rails 2 :

class User < ActiveRecord::Base
 has_many :addresses

 named_scope :group_by_city, joins(:addresses).where(["addresses.city = ?", "Jakarta"])
end

Rails 3 above :

class User < ActiveRecord::Base
 has_many :addresses

 scope :group_by_city, joins(:addresses).where(["addresses.city = ?", "Jakarta"])
end

 

Share

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>