[英]Better routes in rails with params
I've been working on a movie application in Rails. 我一直在Rails中开发电影应用程序。 I have a controller/view for the actor.
我有演员的控制器/视图。 When passing params to the actors controller i want the URL to be pretty.
当将参数传递给actors控制器时,我希望URL很漂亮。 Now it looks like this:
http://localhost:3000/actors/show?actor=Hayley+Atwell
and i want it to look like /actors/show/Hayley+Atwell
or /actors/Hayley+Atwell
. 现在看起来像这样:
http://localhost:3000/actors/show?actor=Hayley+Atwell
,我希望它看起来像/actors/show/Hayley+Atwell
或/actors/Hayley+Atwell
。
How do i do this? 我该怎么做呢? My link in the movies view is:
我在电影视图中的链接是:
<%= link_to a.name, {:controller => 'actors', :action => 'show', :actor => a.name}, :class => "label label-default" %>
My routes.rb is now like this: 我的routes.rb现在像这样:
get 'actors/show'
I recommend you use friendly_id gem. 我建议您使用friendly_id gem。 It perfectly satisfies your needs!
它完全可以满足您的需求!
https://github.com/norman/friendly_id https://github.com/norman/friendly_id
您可以在./config/route.rb文件中使用以下命令:
get '/actors/:actor', to: 'actors#show'
I'll give a series of refactoring advice as follow: 我将给出一系列重构建议,如下所示:
Then, you can now change the link in your view to something like: 然后,您现在可以将视图中的链接更改为:
<%= link_to a.name, {:controller => 'actors', :action => 'show', :id => a.id}, :class => "label label-default" %>
Note: the
:
part in the:id
of your route means that this could be interchanged to anything, and whatever comes in that place will be interpreted as theid
.注意:路线
:id
中的:
部分表示可以将其交换为任何内容,并且该位置出现的任何内容都将被解释为id
。 So, in/actors/show/7
, the id of the actor is 7, you can now find the actor with thisid
in your controller action, and do anything you want with it.因此,在
/actors/show/7
,actor的ID为7,您现在可以在控制器动作中找到具有该id
的actor,并对其进行任何操作。
If I'm right than you try to create RESTful
routes anyway. 如果我是对的,那么无论如何,您都尝试创建
RESTful
路由。
So I would recommend you to use the Rails' resources
method in your routes: 因此,我建议您在路线中使用Rails的
resources
方法 :
Rails.application.routes.draw do
resources :actors # If you want only the :show action than add:
# , only: [:show]
end
This automatically creates the proper routes for you. 这会自动为您创建正确的路线。
To get the names
into the URL you should use the friendly_id gem . 要将
names
放入URL中,应使用friendly_id gem 。 It has a great community and is very well tested. 它有一个很棒的社区,并且经过了很好的测试。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.