· 1 min read

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)

Comments

Leave a comment