Rails 3 - 如何设置 example.com/whatever-i-need 的路线
我有一个小数据库,里面有我看过的电影。现在,当我想显示电影的详细信息时,所需电影的个人资料位于地址 example.com/movies/21
上。 但我希望在更好的 URL 地址上有每部电影的个人资料页面,例如 example.com/lords-of-the-rings
。
我该怎么做呢?
I have a little database with a movies that I saw. Now when I want to display a detail of a movie, so the profile of wanted movie is on the address example.com/movies/21
.
But I would like to have a profile page of every movie on the nicer URL address, for example example.com/lords-of-the-rings
.
How can I do it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在您的模型中,将 url 名称存储到一个新字段中,例如
Movie.permalink
在
config/routes.rb
中:以及在您的控制器中:
有关 Rails 中路线的更多信息: http://guides.rubyonrails.org/routing.html
In your model, store the url name into a new field, like
Movie.permalink
In
config/routes.rb
:And in your controller :
For more on routes in rails : http://guides.rubyonrails.org/routing.html
考虑使用 slugged gem: https://github.com/Sutto/slugged
许多人喜欢这种方法。
这是轨道 3+
Consider using the slugged gem: https://github.com/Sutto/slugged
Many folks like this approach.
It's rails 3+
只是为了帮助指导答案,您是否允许类似以下内容:
如果是这样,从该 URL 获取 params[:id] 很容易。
您可以通过更改模型的 to_param 自动生成最后一个 :id:
然后您可以更改控制器的 show 方法以反映新的 :id 格式。
Just to help guide the answers, would you allow something like:
If so, grabbing the params[:id] from that URL is easy.
You can automate the generation of that last :id by changing to_param of the model:
Then you could change the show method of the controller to reflect the new :id format.