Adam Templeton
Adam Templeton

Reputation: 4617

Rails: Adding text to a route's URL

Is it possible to append text to a route's URL, so instead of, say,

http://site/page/2

it comes out

http://site/page/2-cool-stuff-here

?

Upvotes: 1

Views: 385

Answers (2)

Colin R
Colin R

Reputation: 17751

Since you appear to be okay with keeping the object's id in the url, you can override to_param like so:

class Article < ActiveRecord::Base
  def to_param
    "#{id} #{name}".parameterize
  end
end

which would return .../articles/1-[article name] (As pointed out by the FriendlyId RailsCast mentioned by @Benjamin Tan).

If you desire more functionality than just that, you should check out the FriendlyId gem (see the RailsCast link above).

Upvotes: 3

Related Questions