to_param

to_param(method_name = nil)
Instance Public methods

Defines your model's to_param method to generate âprettyâ URLs using method_name, which can be any attribute or method that responds to to_s.

1
2
3
4
5
6
7
class User < ActiveRecord::Base
  to_param :name
end
 
user = User.find_by(name: 'Fancy Pants')
user.id         # => 123
user_path(user) # => "/users/123-fancy-pants"

Values longer than 20 characters will be truncated. The value is truncated word by word.

1
2
3
user = User.find_by(name: 'David HeinemeierHansson')
user.id         # => 125
user_path(user) # => "/users/125-david"

Because the generated param begins with the record's id, it is suitable for passing to find. In a controller, for example:

1
2
params[:id]               # => "123-fancy-pants"
User.find(params[:id]).id # => 123
doc_ruby_on_rails
2025-01-10 15:47:30
Comments
Leave a Comment

Please login to continue.