Skip to content

Keep Finders on Their Own Model

Richard Huang edited this page Aug 15, 2010 · 3 revisions

Please go to http://rails-bestpractices.com/posts/13-keep-finders-on-their-own-model

Before:


class Post < ActiveRecord::Base
  has_many :comments

  def find_valid_comments
    self.comment.find(:all, :conditions => {:is_spam => false},
                            :limit => 10)
  end

end

class Comment < ActiveRecord::Base
  belongs_to :post
end

class CommentsController < ApplicationController

  def index
    @comments = @post.find_valid_comments
  end

end

After:


class Post < ActiveRecord::Base
  has_many :comments
end

class Comment < ActiveRecord::Base
  belongs_to :post

  named_scope :only_valid, :conditions => { :is_spam => false }
  named_scope :limit, lambda { |size| { :limit => size } }
end

class CommentsController < ApplicationController

  def index
    @comments = @post.comments.only_valid.limit(10)
  end

end