Reputation:
I have created a blog and I want when I browse a post to use its title on the URL rather than the default "posts/[:id]", e.g. posts/1 or posts/2.
I did place this code-segment to post.rb file
def to_param
title
end
which represents the post's title. The issue is that titles may have spaces like "Welcome to the blog" title and this leads to errors when I try to link to the post's page.
I have seen other platforms like Wordpress that automatically replace spaces with dashes. But I don't have a clue how to do this in Rails.
Any idea or guidance to the correct direction will be helpful.
Upvotes: 1
Views: 257
Reputation: 4959
You'll want to call parameterize on the title
def to_param
title.parameterize
end
This will make it a friendly URL with the spaces replaced by dashes. I believe if you don't include the id before title Active Record's find
won't work. This would require you to have:
def to_param
"#{id} #{title}".parameterize
end
If you are looking for more versatility check out Friendly ID gem and this railscast: http://railscasts.com/episodes/314-pretty-urls-with-friendlyid?view=asciicast
Mainly be careful that your routes and calls still work after you make the changes.
Upvotes: 2