为什么在rails 2中使用link_to时要在路由文件中添加连接
我试图完成以下任务:
<%= link_to "注销", { :controller => '用户', :action => '注销' }, :class =>; 'menulink2' %>
但它不起作用,它总是将我重定向到显示视图。我必须将以下内容添加到我的routes.rb中:
map.connect '用户/注销', :控制器=> '用户', :action => '注销'
为什么 Rails 无法识别我正在传递的操作('logout')?
I was trying to accomplish the following:
<%= link_to "Log out", { :controller
=> 'users', :action => 'logout' }, :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:
map.connect 'users/logout',
:controller => 'users', :action =>
'logout'
Why didn't rails recognize the action I was passing ('logout') ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
该逻辑必须在某处指定。必须有一些来自哈希
{:controller =>; 的映射。 '用户', :action => 'logout'}
到一个 url,而在 Rails 中完成的地方是routes.rb
文件。在旧版本的 Rails 中,许多routes.rb
在末尾带有默认值:map.connect ':controller(/:action/(:id(.:format)))'< /code>
这将使大多数 :controller, :action 哈希值可以被指定,然后路由到
host.url/:controller/:action
。随着更现代的版本,基于资源的路由受到极大的青睐,并且控制器不遵循 Rails 的 REST 约定(即只有
:index,:show,:create,:new,:edit,:update,: destroy
方法)通常必须以某种方式显式指定其路由。(使用
map.resources :users, :collection => {:get => :logout}
或使用map.connect( 'some_url', :controller => 'users ', :action => 'logout'})
)我猜,但他们这样做的原因可能是控制器的操作实际上只是它的公共方法。
在控制器中拥有不是用于测试目的的 url 端点的公共方法通常是件好事。
例如,您可以将
before_filter
作为您可能想要测试的公共方法,而不必在测试代码中使用@controller.send(:your_before_filter_method)
。因此,他们将资源操作列入白名单,并默认使其他操作无法访问。让我浏览一下 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 theroutes.rb
file. In older versions of rails manyroutes.rb
came with a default at the end: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
.With the more modern versions resource-based routes are heavily favored, and controllers which don't follow rails' REST conventions (i.e. having only
:index,:show,:create,:new,:edit,:update,:destroy
methods) generally have to have their routes explicitly specified in some way.(Either with
map.resources :users, :collection => {:get => :logout}
or withmap.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.
It's frequently nice to have public methods in your controllers that aren't url-end-points for testing purposes.
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.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.