[英]Why to add a connection in routes file when using link_to in rails 2
I was trying to accomplish the following:我试图完成以下任务:
<%= link_to "Log out", {:controller => 'users', :action => 'logout' }, :class => 'menulink2' %> <%= link_to "注销", {:controller => '用户', :action => '注销' }, :class => 'menulink2' %>
But it didn't work, it always redirected me to a show view.但它没有用,它总是将我重定向到一个显示视图。 I had to had the following to my routes.rb:我的 routes.rb 必须有以下内容:
map.connect 'users/logout', :controller => 'users', :action => 'logout' map.connect '用户/注销', :controller => '用户', :action => '注销'
Why didn't rails recognize the action I was passing ('logout')?为什么 Rails 无法识别我正在传递的操作(“注销”)?
That logic has to be specified somewhere.该逻辑必须在某处指定。 There's got to be some mapping from the hash {:controller => 'users', :action => 'logout'}
to a url, and the place that's done in rails is the routes.rb
file.从 hash {:controller => 'users', :action => 'logout'}
到 Z572D4E421E5E6B9BC11D815E8A02 中完成的routes.rb
文件必须有一些映射。 In older versions of rails many routes.rb
came with a default at the end:在旧版本的 rails 中,许多routes.rb
在末尾带有一个默认值:
map.connect ':controller(/:action/(:id(.:format)))'
Which would make it so that most any:controller, :action hash could be specified and then routed to host.url/:controller/:action
.这将使大多数:controller, :action hash 可以被指定,然后路由到host.url/:controller/:action
。
With the more modern versions resource-based routes are heavily favored, and controllers which don't follow rails' REST conventions (ie having only :index,:show,:create,:new,:edit,:update,:destroy
methods) generally have to have their routes explicitly specified in some way.在更现代的版本中,基于资源的路由受到青睐,并且控制器不遵循 rails 的 REST 约定(即只有:index,:show,:create,:new,:edit,:update,:destroy
方法)通常必须以某种方式明确指定它们的路线。
(Either with map.resources:users, :collection => {:get =>:logout}
or with map.connect( 'some_url', :controller => 'users', :action => 'logout'})
) (要么带有map.resources:users, :collection => {:get =>:logout}
map.connect( 'some_url', :controller => 'users', :action => 'logout'})
I'm guessing, but the reason they did that is probably that the actions of a controller are really just its public methods.我猜,但他们这样做的原因可能是 controller 的行为实际上只是它的公共方法。
It's frequently nice to have public methods in your controllers that aren't url-end-points for testing purposes.在您的控制器中拥有不是用于测试目的的 url-end-points 的公共方法通常很好。
For instance, you could have before_filter
s as public methods that you might want to test without having to use @controller.send(:your_before_filter_method)
in your test code.例如,您可以将before_filter
作为您可能想要测试的公共方法,而不必在测试代码中使用@controller.send(:your_before_filter_method)
。
So they whitelist the resource actions, and make the others unreachable by default.因此,他们将资源操作列入白名单,并默认使其他操作无法访问。 Let me look through the rails changelog and see if I'm right.让我看一下rails changelog,看看我是不是对的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.