在Rails 3.0.4中没有匹配路由

5

我已经盯着这个问题看了一段时间。当我尝试查看页面时,出现了以下错误。

No route matches {:action=>"confirm", :controller=>"locations"}

这是我在视图中拥有的内容。

<%= form_for(@location, :url => { :action => :confirm }) do |f| %>
<% end %>

我认为我的路由文件设置正确。

Finder::Application.routes.draw do
  resources :locations do
    member do 
      post :confirm
    end
  end

  root :to => 'locations/index'
end

有什么想法吗?

更新:

运行rake routes,我认为得到了正确的结果。

confirm_location POST   /locations/:id/confirm(.:format) {:action=>"confirm", :controller=>"locations"}
4个回答

5
在未来,您可以通过运行$ rake routes并查看输出轻松调试路由。 ;)
我认为发生的情况是您的post:confirm没有注册您期望的路由。在指南中,match及其类似物接受像这样的URL段字符串:
resources :locations do
  member do
    post 'confirm'
  end
end

请注意,现在的“confirm”是一个字符串而不是一个符号。
如果这不能帮助您,请运行$ rake routes,并将输出附加到您的问题中。
更新
在查看您的rake输出后,我认为您只需要在您的form_for上指定POST方法:
<%= form_for(@location, :url => { :action => :confirm }, :method => :post) do |f| %>
<% end %>

你可以使用Rails定义的辅助方法,使这个更易读:

您也可以使用Rails定义的辅助方法使其更易于阅读:

<%= form_for(@location, :url => confirm_location_path(@location), :method => :post) do |f| %>
<% end %>

谢谢,@coreyward。按照你建议的重写代码后,问题似乎已经暴露出来了。由于@location还没有一个id,所以这个路由不能起作用是有道理的。 - Garrett Murphey
@Garrett:这很有道理。很高兴我们解决了这个问题。你可能可以从form_for中删除method参数。对于资源路由对象,它是不需要的,但如果你使用自定义的url参数,你可能会发现它是必需的。一旦你让事情正常工作,稍微探索一下就能确定是否需要。 - coreyward

1
尝试在你的form_for中添加:method => :post
<%= form_for(@location, :url => { :action => :confirm }, :method => :post) do |f| %>
<% end %>

1

如果您在路由文件中声明了仅接受POST请求的路由,确保form_for不会悄悄地插入一个带有_method = put的隐藏字段。


1

你在 LocationsController 中定义了 confirm 操作吗?


猜得不错,但这不是问题所在;他在查看表单时遇到错误,因为隐式的 url_for 无法找到为他指定的参数定义的路由。 - coreyward

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接