R – Implementing an ActiveRecord before_find

activerecordcallback

I am building a search with the keywords cached in a table. Before a user-inputted keyword is looked up in the table, it is normalized. For example, some punctuation like '-' is removed and the casing is standardized. The normalized keyword is then used to find fetch the search results.

I am currently handling the normalization in the controller with a before_filter. I was wondering if there was a way to do this in the model instead. Something conceptually like a "before_find" callback would work although that wouldn't make sense on for an instance level.

Best Answer

You should be using named scopes:

class Whatever < ActiveRecord::Base

  named_scope :search, lambda {|*keywords|
    {:conditions => {:keyword => normalize_keywords(keywords)}}}

  def self.normalize_keywords(keywords)
    # Work your magic here
  end

end

Using named scopes will allow you to chain with other scopes, and is really the way to go using Rails 3.