Understand Named_scope in 60 seconds

June 28th, 2009

Named scope was introduced in Rails 2.x, it allows you to filter a selection of records easily and repeatedly, without having to write finder SQL all the time.

class Customer < ActiveRecord::Base
  has_many :carts
end

class Cart < ActiveRecord::Base
  belongs_to :customer
  named_scope :completed, :conditions => ["NOT ISNULL(completed_at)"]
end



Example of self-model scoping and finding:

# All completed carts - equivalent of previously writing: Cart.find(:all, :conditions => "NOT ISNULL(completed_at)")
Cart.completed



Here are some examples showing cross-model scoping and finding:

# All carts for a customer
@customer.carts

# Just the completed carts belonging to a customer
@customer.carts.completed

Categories: Rails, activerecord

Tags: , , Leave a comment

Like This Post?

Subscribe for more...

1 Comment

  1. Horace Ho

    Well explained. Thank you!

Feed

http://www.mendable.com / Understand Named_scope in 60 seconds