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
[...] This post was mentioned on Twitter by Ruby Brasil and Igor Lanes , Allen Walker. Allen Walker said: Rails ActiveRecord callbacks and destructive methods http://www.railswizard.com/2011/02/12/activerecord-callbacks-and-destructive-methods/ [...]
Tweets that mention ActiveRecord callbacks and destructive methods « Rails Wizard -- Topsy.com
February 14, 2011