Skip to main content

Close
Get the best research tool on the web today,and free!
Connect with people with common interests!

saved by4 people, first byMyles A Braithwaite on 2006-07-25, last bylei zhou on 2008-06-10

  • Implementing this is extremely simple, because Rails treats :id as a special parameter in routes. It’s specialness comes from the fact that it would try to call the to_param method on any object passed when creating URLs. That’s why url_for :id => @account is equivalent to url_for :id => @account.id, because ActiveRecord model’s have a default to_param that returns the id of the object.
  • All you need to do is define your own to_param for your models, and make sure you don’t explicitly include the .id in your url_fors and link_tos, because then you would be skipping your own to_param call.


    class Account < ActiveRecord::Base
    def to_param
    "#{id}-#{full_name.gsub(/[^a-z1-9]+/i, '-')}"
    end
    end
  • The second part of this solution is, of course, making sure your actions can handle these extended :ids.
  • It’s just that Rails will pass your long :id string to the database server, which, on seeing that the id column is actually an integer, will try to convert the parameter to a number before using it, and it happens that such conversion will just use any numerical characters it finds and drop the rest, thus converting “12-john-doe” into plain 12.