Your browser (Internet Explorer 6) is out of date. It has known security flaws and may not display all features of this and other websites. Learn how to update your browser.
X

ActiveRecord callbacks and destructive methods

Recently I added search functionality to my application. I implemented a search controller and model. An issue I faced was manipulating the search keywords entered by the user so the search query worked properly. I ended up doing the following:

search.rb

class Search < ActiveRecord::Base
  belongs_to :user
  attr_accessible :keywords, :category, :user
 
  validates_presence_of :keywords
 
 # DON'T CHAIN DESTRUCTIVE METHODS!
  before_save Proc.new{|search| search.keywords.strip!.downcase!}
 
  #....
end

I got some really weird behavior when the before_save callback fired and later learned not to chain destructive methods!
See this for more information.

So the solution was:

before_save Proc.new{|search| search.keywords = search.keywords.strip.downcase}

Alternatively I could implement a method to trim and downcase the keywords also:

before_save :clean_keywords
 
def clean_keywords
   keywords = keywords.strip.downcase
end

Leave a comment  

name*

email*

website

Submit comment