Not So Stupid » Blog Archive » URLs on Rails
Popularity Report
![]() |
|||
![]() |
|||
![]() |
|||
![]() |
|||
![]() |
|||
![]() |
Groups (1)
Bookmark History
Public Sticky notes
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.
Highlighted by vincent
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
Highlighted by vincent
The second part of this solution is, of course, making sure your actions can handle these extended :ids.
Highlighted by vincent
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.
Highlighted by vincent


Public Comment