Rails and the to_param hack

Rails and the to_param hack  

Wednesday, June 03 2009

I didn’t really know how to_param works till lifo pointed it out to me. Apparently, Rails uses a db hack to make to_param work the way it is.

Let me explain with an example:

def to_param
  #{id}-#{underscored_name}
end

Your to_param string needs to begin with #{id} or it doesn’t work! The reason for that is that rails doesn’t do anything with an incoming params[:id] string like “5-Rails-and-the-to_param-hack”, it just generates the query:

SELECT * from pages WHERE id = "5-Rails-and-the-to_param-hack" 

and the database returns the row with id = ‘5’, it doesn’t care about what comes after the 5.

Fancy, but mad ugly hack.


  • Posted by Aditya

Posted by Aditya on 03 Jun 2009