Skip to main content

Not So Stupid » Blog Archive » URLs on Rails

Popularity Report

Total Popularity Score: 0

Loading...
Loading...
Loading...
Loading...
Loading...
Loading...

Rank

URL Tag Cloud

Groups (1)

  • rubyonrails

    Ruby on Rails

    44 members,162 bookmarks

    Ruby on Rails Web Development Framework resources

Bookmark History

Saved by 4 people (0 private), first by anonymouse user on 2006-07-25


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