Search code examples
ruby-on-railsrubyurlmodellimit

How to Limit URL: "#{id} #{name}".parameterize


When a user creates a valuation (aka value) the :name of that valuation becomes part of the url because of this method:

valuation.rb

def to_param
  "#{id} #{name}".parameterize
end

For example if the user creates a value:

Once more into the fray. The last good fight I’ll ever know. Live and die on this day. Live and die on this day.

The url would be http://www.personalcontrolcenter.com/valuations/33-once-more-into-the-fray-the-last-good-fight-i-ll-ever-know-live-and-die-on-this-day-live-and-die-on-this-day

That is waaaaaay too long. I'd like to limit it to 15 characters. Here were my attempts:

#1

def to_param
  "#{id} #{name}".limit(15).parameterize # undefined method limit error
end

#2

def to_param
  ["#{id} #{name}".limit(15)].parameterize # undefined method limit error
end

#3

def to_param
  "#{id} #{name}".parameterize.limit(15) # undefined method limit error
end

Solution

  • "#{id} #{name}".parameterize.first(15)