imjp
imjp

Reputation: 6695

Creating seo friendly url from a string

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

Answers (3)

Tamik Soziev
Tamik Soziev

Reputation: 14798

The best thing is to use parameterize method:

name = name.parameterize

Inflector#parameterize

Upvotes: 34

Ola Karlsson
Ola Karlsson

Reputation: 107

check out the has_permalink gem I've created at http://haspermalink.org

That gem will help you solve that.

Upvotes: 2

Dex
Dex

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

Related Questions