Easily build a great vocabulary without studying! Now on the App Store!
Click here for more info about the app

named_scope in Rails


Take advantage of the named_scope method in your models and make find queries simple and beautiful!

class Comment < ActiveRecord::Base
  belongs_to :post
  named_scope :pending, :conditions => ["pending = ?", true]
  named_scope :for, lambda { |*args| {:include => :post,
      :conditions => ["posts.account_id = ?", (args.first||0)] }}

class Post < ActiveRecord::Base
  has_many :comments

Now you can get all comments for your posts that are marked as pending with this method:

@comments = Comment.pending.for(@account.id)
Tagged w/ #ruby on rails