RubyGreenBlue

Using with_scope the Right Way

Posted by keith 8 months ago

Most examples of with_scope I've seen floating around the web seemed to be to be going about it the wrong way.

Stuff like this wedged in with some other code:

Article.with_scope(:find => {:conditions => "published = 1"]}) do
  Article.find(:all) # or some other find operations.
end

To me that's a bit arse-about and even a little messy to stick in the middle of some other code.

A much nicer way is to use the with_scope method to help craft one's own specialised find methods. With the following example, the above code could be replaced with a much nicer looking call to Article.find_published(:all):

class Article < ActiveRecord::Base

  def self.find_published(*args)
    with_scope(:find => {:conditions => "published = 1"}) do
      find(*args)
    end
  end

end

Some other examples of use:

@published = Article.find_published(:all)
@published_today = Article.find_published(:all, :conditions => ["published_at >= :today", {:today = Date.today}])

To me, that is a much neater way to use with_scope. I also find these type of find methods help remove business logic from controllers and put it back into models where it belongs. The definition of a published article is a matter for a model class rather than a controller.