Ecommerce Developer
 
 

Code

Tutorial: Active Record's named_scope Method for Ruby on Rails

 

This screencast covers Active Record's namedscope_ method. Namedscope_ adds a class method that returns objects meeting specified criteria. Named scopes are commonly used to identify a grouping of objects based on some common criteria such as "active," "past_due," or "color."

In this screencast, we use apply namedscopes_ to our screencast model. To help demonstrate the power and elegance of named scope, we first look at how similar requirements would be met prior to this option. This approach also helps to demonstrate what named scope is doing and how to implement it.

Working through the screencast results in two named_scopes added to our model.

  
named_scope :archived, :conditions => ['published_on < ?',
Date.today - 30.days]

  named_scope :of_topic, lambda { |topic|
    { :conditions => ['topic = ?', topic] }
  }

Resources

Related Articles

1 Comment

Rss-sm