使 Rails 资源和自定义路由冲突发挥作用
我是 Rails 新手,想知道如何才能完成这项工作。我希望 URL 看起来像这样:
http://localhost:3000/businesses/coldfire-gundam
使用此路由:
match "/businesses/:permalink", :to => "businesses#show", :as => :business_permalink
但是,当我将此路由放在此之前时:
resources :businesses
任何对 /businesses/1 (1 as param[:id]) 的调用都不再起作用,显然是因为它被永久链接声明
我怎样才能让它工作呢?
I am new to rails and was wondering how I can make this work. I want a URL to look like this:
http://localhost:3000/businesses/coldfire-gundam
using this route:
match "/businesses/:permalink", :to => "businesses#show", :as => :business_permalink
however when I place this route before this:
resources :businesses
any call to /businesses/1 (1 as param[:id]) does not work anymore, obviously because it is caught by the permalink declaration
how can I make it work then?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要一种方法来区分
/businesses/:id
和/businesses/:permalink
。:id
应始终为数字(当然,除非您使用 MongoDB),因此如果您可以强制:permalink
始终包含非数字内容,那么一个简单的 < code>:constraints 应该可以解决问题:/.*\D/
强制路由仅在:permalink
包含至少一个非数字时匹配特点。您需要.*
因为路由正则表达式隐式锚定在开头。如果您碰巧使用 MongoDB,那么您的
:id
可能是十六进制 BSON ID,因此您需要使用/.*\H/
作为约束,并且您想要某种方法来确保您的:permalink
始终包含至少一个非十六进制字符。一切就绪后,您可以将
match "/businesses/:permalink"
放在routes.rb
中的resources :businesses
之前,一切都应该工作正常。路由的检查顺序与它们在routes.rb
中出现的顺序相同,因此您需要在resources
之前添加match
。You need a way to differentiate
/businesses/:id
and/businesses/:permalink
. The:id
should always be numeric (unless of course you're using MongoDB) so if you can force your:permalink
to always contain something non-numeric then a simple:constraints
should do the trick:The
/.*\D/
forces the route to only match if:permalink
contains at least one non-numeric character. You need the.*
because route regexes are implicitly anchored at the beginning.If you happen to be using MongoDB then your
:id
will probably be a hex BSON ID so you'd want to use/.*\H/
as your constraint and you'd want some way to ensure that your:permalink
always contains at least one non-hex character.Once all that's in place you can put your
match "/businesses/:permalink"
before yourresources :businesses
inroutes.rb
and everything should work fine. And routes are checked in the same order that they appear inroutes.rb
so you will want yourmatch
before yourresources
.我建议使用Friendly_id gem 来创建永久链接路由。这将以一种易于重用的方式为您处理大部分“魔法”。
gem 和 Railscast 的资源:
https://github.com/norman/friend_id
http://railscasts.com/episodes/314-pretty-urls-with-friendidid
I would suggest using the friendly_id gem for creating permalink routes. This will handle most of the 'magic' for you in an easily reusable way.
Resources for the gem and railscast:
https://github.com/norman/friendly_id
http://railscasts.com/episodes/314-pretty-urls-with-friendlyid