Reputation: 6695
I am trying to create a URL friendly link from a string. Instead of example.com/Jessica Alba
, I want example.com/jessica-alba
. How do I get the link_to tags to link me to the seo friendly permalink?
I also need to make sure that the show method only displays the seo friendly permalink in the address bar and only accepts the seo friendly permalink.
Upvotes: 9
Views: 5734
Reputation: 14798
The best thing is to use parameterize method:
name = name.parameterize
Upvotes: 34
Reputation: 107
check out the has_permalink gem I've created at http://haspermalink.org
That gem will help you solve that.
Upvotes: 2
Reputation: 12749
You can override the to_param
method in your model.
So if you have a model called Celebrity
, which has a name
column you can go:
class Celebrity < ActiveRecord::Base
def to_param
self.name.downcase.gsub(' ', '-')
end
end
Then:
jessica_alba = Celebrity.find_by_name("Jessica Alba")
link_to "Jessica Alba", celebrity_path(jessica_alba)
Upvotes: 4