知道@vendor.name,如何使Ruby on Rails SEO 中的URL 友好? [英] how do I make the URL's in Ruby on Rails SEO friendly knowing a @vendor.name?

查看:32
本文介绍了知道@vendor.name,如何使Ruby on Rails SEO 中的URL 友好?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的申请在 RoR 中

My application is in RoR

我有一个名为 showsummary 的操作/视图,其中 ID 已传递到 URL 中,控制器使用它来实例化 @vendor,其中 @vendor.name 是公司名称.

I have an action/view called showsummary where the ID has been passed into the URL, and the controller has used that to instantiate @vendor where @vendor.name is the name of a company.

我希望 URL 是 URL,而不是在 URL 中包含/vendor-name,而不是 showsummary/1/.

I would like the URL to be, rather than showsummary/1/ to have /vendor-name in the URL instead.

我该怎么做?

推荐答案

所有这些解决方案都使用 find_by_name,这肯定需要在该列上有一个索引并且要求它们是唯一的.我们使用的一个更好的解决方案,牺牲了少量的美观,是使用供应商名称作为其 ID 的前缀.这意味着您不必在名称列上建立索引和/或要求唯一性.

All of these solutions use find_by_name, which would definitely require having an index on that column and require they are unique. A better solution that we have used, sacrificing a small amount of beauty, is to use prefix the vendor name with its ID. This means that you dont have to have an index on your name column and/or require uniqueness.

供应商.rb

def to_param
  normalized_name = name.gsub(' ', '-').gsub(/[^a-zA-Z0-9\_\-\.]/, '')
  "#{self.id}-#{normalized_name}"
end

所以这会给你像

/1-Acme

/19-Safeway

/19-Safeway

然后在你的表演动作中你仍然可以使用

Then in your show action you can still use

Vendor.find(params[:id])

因为该方法将在其参数上隐式调用 .to_i ,并且在这样的字符串上调用 to_i 将始终返回数字前缀并删除剩余的文本 - 全部在那一点上绒毛.

as that method will implicitly call .to_i on its argument, and calling to_i on such a string will always return the numerical prefix and drop the remaining text- its all fluff at that point.

以上假设您使用的是 /:controller/:action/:id 的默认路由,这将使您的 URL 看起来像

The above assumes you are using the default route of /:controller/:action/:id, which would make your URLs look like

/vendors/show/1-Acme

/vendors/show/1-Acme

但是如果你想让它们看起来很简单

But if you want them to just look

/1-Acme

然后有一条路线

map.show_vendor '/:id', :controller => 'vendors', :action => 'show'

这意味着它几乎会吞下很多您可能不想要的 URL.发出警告.

This would imply that that it would pretty much swallow alot of URLs that you probably wouldnt want it too. Take warning.

这篇关于知道@vendor.name,如何使Ruby on Rails SEO 中的URL 友好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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