从字符串创建 seo 友好的 url [英] Creating seo friendly url from a string

查看:41
本文介绍了从字符串创建 seo 友好的 url的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从字符串创建一个 URL 友好链接.我想要 example.com/jessica-alba 而不是 example.com/Jessica Alba.如何获取 link_to 标签以将我链接到 seo 友好永久链接?

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?

我还需要确保 show 方法只在地址栏中显示 seo 友好的永久链接,并且只接受 seo 友好的永久链接.

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.

推荐答案

您可以覆盖模型中的 to_param 方法.

You can override the to_param method in your model.

因此,如果您有一个名为 Celebrity 的模型,它有一个 name 列,您可以:

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

那么:

  jessica_alba = Celebrity.find_by_name("Jessica Alba")
  link_to "Jessica Alba", celebrity_path(jessica_alba)

这篇关于从字符串创建 seo 友好的 url的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆