instance method to_param

Ruby on Rails edge

Since v4.1.16

Available in: v4.1.16 v4.2.11.3 v5.0.7.2 v5.1.7 v5.2.8.1 v6.0.6.1 v6.1.7.10 v7.0.10 v7.1.6 v7.2.4 v8.0.5.1 v8.1.4 edge

Signature

to_param(method_name = nil)

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 # => “123-fancy-pants” User.find(params).id # => 123 “`

Parameters

method_name opt = nil
Source
# File activerecord/lib/active_record/integration.rb, line 171
      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.parameterize.truncate(20, separator: /-/, omission: "")).present?
              "#{default}-#{param}"
            else
              default
            end
          end
        end
      end

Defined in activerecord/lib/active_record/integration.rb line 171 · View on GitHub · Improve this page · Find usages on GitHub

Defined in ActiveRecord::Integration::ClassMethods

Type at least 2 characters to search.

Use the arrow keys to navigate results, Enter to open one, Escape to close.

Keyboard shortcuts

/
Focus search
⌘K / Ctrl-K
Command palette
?
This help
Esc
Close