How do I rewrite URL's based on title?

混江龙づ霸主 提交于 2019-12-01 11:35:40

I used this in an old Rails 2.x app. There may be a better approach to scrubbing the title...

(goes in your model)

def to_param
  seo_uri
end

def seo_uri
  "#{self.id}-#{self.title.gsub(/[^a-z0-9]+/i, '-').gsub(/-{2}/, '-').gsub(/-$/, '')}"
end

Hope this helps!

UPDATE

Comments on this answer indicated there is a new method available for Rails 3 users: #parameterize. The Rails API document for this method shows how it should be used (cut-n-paste):

class Person
  def to_param
    "#{id}-#{name.parameterize}"
  end
end

@person = Person.find(1)
# => #<Person id: 1, name: "Donald E. Knuth">

<%= link_to(@person.name, person_path %>
# => <a href="/person/1-donald-e-knuth">Donald E. Knuth</a>

There's a really awesome plugin, FriendlyId which will handle all this for you. Loads of really clever features, including scopes and handling of 301 redirects on title change. This differs from stackoverflow and Brian's method in that the id isn't used in the url.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!