Kevin
Kevin

Reputation: 635

Rails change to_params url

I currently have this overriding my to_params method in my model

  def to_param
    normalized_name = title.gsub(' ', '-').gsub(/[^a-zA-Z0-9\_\-\.]/, '')
    "#{self.id}-#{normalized_name}"
  end

and the URL shows like this /posts/1-Hello-World-very-nice is it possible to make so that it shows like this /posts/1/Hello-World-very-nice

Upvotes: 0

Views: 1325

Answers (1)

Jits
Jits

Reputation: 9728

You could add a separate route for this, for example:

In your routes file (assuming Rails 3):

match 'posts/:id/:name' => 'posts#show', :as => "show_post"

Then in your view you would need to use the following to generate the correct URL:

show_post_path(@post, :name => @post.normalized_name)

Note that the order in which you put this in your routes file is important, so that your other Post routes don't get overwritten.

Upvotes: 2

Related Questions