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.
Friendly URLs are called Aliases in Sitecore. The benefit of creating a friendly URL is that they are easier to remember and contain key words about the web page. Example: Original URL: https://portal.ct.gov/Services/Education/Higher-Education/Higher-Education-Information-and-Resources.
The best thing is to use parameterize method:
name = name.parameterize
Inflector#parameterize
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)
check out the has_permalink gem I've created at http://haspermalink.org
That gem will help you solve that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With