method
to_param
![Moderate documentation Importance_2](https://d2vfyqvduarcvs.cloudfront.net/images/importance_2.png?1349367920)
Ruby on Rails latest stable (v7.1.3.2)
-
0 notes -
Class: ClassMethods
- 1.0.0
- 1.1.6
- 1.2.6
- 2.0.3
- 2.1.0
- 2.2.1
- 2.3.8
- 3.0.0
- 3.0.9
- 3.1.0
- 3.2.1
- 3.2.8
- 3.2.13
- 4.0.2
- 4.1.8 (0)
- 4.2.1 (0)
- 4.2.7 (0)
- 4.2.9 (0)
- 5.0.0.1 (3)
- 5.1.7 (38)
- 5.2.3 (0)
- 6.0.0 (0)
- 6.1.3.1 (0)
- 6.1.7.7 (0)
- 7.0.0 (0)
- 7.1.3.2 (0)
- 7.1.3.4 (0)
- What's this?
to_param(method_name = nil)
public
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.
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.
user = User.find_by(name: 'David Heinemeier Hansson') user.id # => 125 user_path(user) # => "/users/125-david-heinemeier"
Because the generated param begins with the record’s id, it is suitable for passing to find. In a controller, for example:
params[:id] # => "123-fancy-pants" User.find(params[:id]).id # => 123