I don't know about you but every time some news come out about Ruby on Rails, I'm saying to myself: "there is no way this can be any better that it already is". And every time, they manage to find a way to impress me.
This time around, Ryan Daigle talks about the new named_scope feature in his "What's New in Edge Rails: Has Finder Functionality" article.
This basically let you define methods to your ActiveRecord objects which will simplify future queries. For those of you who haven't caught on the Rails train yet, just imagine an ActiveRecord object as an abstraction to a database table, getting all the tables' fields as properties and providing easy SQL requests. And that's a given for a long time in the Rails community.
Now, what named_scope adds is a way to define queries as methods. Let's see Ryan's sample to see how powerful this is:
class User < ActiveRecord::Base named_scope :active, :conditions => {:active => true} named_scope :inactive, :conditions => {:active => false} named_scope :recent, lambda { { :conditions => ['created_at > ?', 1.week.ago] } } end # Standard usage User.active # same as User.find(:all, :conditions => {:active => true}) User.inactive # same as User.find(:all, :conditions => {:active => false}) User.recent # same as User.find(:all, :conditions => ['created_at > ?', 1.week.ago]) # They're nest-able too! User.active.recent
Isn't that a great way to make simple or more complex queries ? Some of the advantages I see are:
User.active.recent
" to request for the most recent active users !Even though once again I don't imagine something better can come out from Rails' master minds, I'll be careful enough and keep this thought to myself !
Recent comments
14 years 12 weeks ago
14 years 12 weeks ago
14 years 12 weeks ago
14 years 12 weeks ago
14 years 13 weeks ago
14 years 29 weeks ago
16 years 1 week ago
16 years 2 weeks ago
16 years 18 weeks ago
16 years 18 weeks ago