Rails 使用Friendly_id gem 按资源名称路由访问
我有一个存储在 City
表中的城市列表。假设我想生成可通过此示例中的 resource.name
、city.name
访问的动态路由。
我希望能够访问 /amsterdam
或 /berlin
。如何?
有关信息,我正在使用 Friendly_id gem,因此已经有了 slug 列(如果这更有意义)。
I have a list of cities stored in City
table. Let's say I want to generate dynamic routes to be accessible through resource.name
, city.name
in this example.
I want to be able to visit /amsterdam
or /berlin
. How?
For info I'm using friendly_id gem so already have slug column if that makes more sense.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
假设您已正确设置Friendly_id:
或
从Friendly_id的快速入门 a> gem:
另外:
这里有一个 RailsCast: http://railscasts.com/episodes/314-pretty-urls-with-friendid?view=asciicast
Assuming you have friendly_id set up correctly:
or
From the Quick Start for the friendly_id gem:
Also:
Here is a RailsCast on it: http://railscasts.com/episodes/314-pretty-urls-with-friendlyid?view=asciicast
在路线文件的末尾添加以下内容:
然后在您的 CitiesController 中:
At the end of your routes file, add this:
Then in your CitiesController:
不知道这是否有帮助..但我已经整理了我在项目中使用的要点。
https://gist.github.com/1908782
它主要适用于我所做的事情,因为我的路线文件是一般来说相当简洁。
它的美妙之处在于,如果您尝试访问一条不存在的路径,它不会碰到任何路线!
顺便说一句,这个在 4.0 版本中被打破了。在撰写本文时,您需要将以下内容放入您的 gemfile 中。
或
希望这有帮助。
Don't know if this helps .. but I have put together a gist on what I use in my projects.
https://gist.github.com/1908782
It mostly works for what I do as my routes file is generally quite concise.
The beauty of it is, that if you attempt to visit a path that doesn't exist, it won't hit any routes!
Just a side note, this is broken in the 4.0 release. At the time of writing this, you will need to put the following in your gemfile.
or
Hope this helps.