module ActiveRecord::Integration::ClassMethods
def to_param(method_name = nil)
params[:id] # => "123-fancy-pants"
suitable for passing to +find+. In a controller, for example:
Because the generated param begins with the record's +id+, it is
user_path(user) # => "/users/125-david"
user.id # => 125
user = User.find_by(name: 'David HeinemeierHansson')
is truncated word by word.
Values longer than 20 characters will be truncated. The value
user_path(user) # => "/users/123-fancy-pants"
user.id # => 123
user = User.find_by(name: 'Fancy Pants')
end
to_param :name
class User < ActiveRecord::Base
responds to +to_s+.
using +method_name+, which can be any attribute or method that
Defines your model's +to_param+ method to generate "pretty" URLs
def to_param(method_name = nil) if method_name.nil? super() else define_method :to_param do if (default = super()) && (result = send(method_name).to_s).present? && (param = result.squish.truncate(20, separator: /\s/, omission: nil).parameterize).present? "#{default}-#{param}" else default end end end end