Topic: Apply a condition to all find queries


I had a quick question regarding find. Say I have the following line

Movie.find(:all, :conditions => ["rating = ?", 5])

Is there any way I can use Movie's Model class to have the condition occur every time I call find, without having to go to every instance of Movie.find in my controllers and manually add it? I'd seem something about after_find but couldn't figure out how to get that to work...


Re: Apply a condition to all find queries

There are plugins out there that do this. Danger even wrote an excellent tutorial on creating a plugin to do this.

However, after reading this post on finding and scoping (it even uses the same Movie example, coincidence?), I think that doing automatic conditions hides some important details about the find and is not as easy to understand. For example, by just looking at one "find" line of code, you don't expect extra conditions to be hidden in that find.

Therefore, instead of automatically scoping every find behind the scenes, it is better to create a method which does the scoping:

class Movie < ActiveRecord::Base
  def self.find_best(*args)
    with_scope :find => { :conditions => ["rating = ?", 5] } do

This way you can call the find like this:

Movie.find_best(:all) # add any other conditions you want

Now it is obvious that a custom find is being called which has extra conditions.

Railscasts - Free Ruby on Rails Screencasts