Module: ActiveRecord::Integration::ClassMethods

Defined in:
lib/rubypitaya/app-template/vendor/bundle/ruby/3.1.0/gems/activerecord-7.0.4/lib/active_record/integration.rb

Instance Method Summary collapse

Instance Method Details

#collection_cache_key(collection = all, timestamp_column = :updated_at) ⇒ Object

:nodoc:



163
164
165
# File 'lib/rubypitaya/app-template/vendor/bundle/ruby/3.1.0/gems/activerecord-7.0.4/lib/active_record/integration.rb', line 163

def collection_cache_key(collection = all, timestamp_column = :updated_at) # :nodoc:
  collection.send(:compute_cache_key, timestamp_column)
end

#to_param(method_name = nil) ⇒ Object

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


147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
# File 'lib/rubypitaya/app-template/vendor/bundle/ruby/3.1.0/gems/activerecord-7.0.4/lib/active_record/integration.rb', line 147

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