4 Apr 2009, 8:39pm
Ruby on Rails
by

leave a comment

named_scope in Rails

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

#app/models/comment.rb
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)] }}
end

#app/models/post.rb
class Post < ActiveRecord::Base
  has_many :comments
end

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

@comments = Comment.pending.for(@account.id)