named_scope snippets

How to use named_scope in Rails

Tagged named_scope, rails, activerecord, ruby  Languages ruby

Simple example of how to use the named_scope feature:

class Feed < ActiveRecord::Base
 
  named_scope :active, :conditions => "(active = 1)"
  named_scope :stale,  :conditions => ["last_updated > ?", 30.minutes.ago.to_s(:db)]

Usage:

Feed.active # return the active feeds

Chaining is also possible:

Feed.active.stale # return the feeds that need to be updated