url_for方法找不到路由

Don*_*ato 5 ruby-on-rails ruby-on-rails-3.1

我必须在一个页面上设置多个表的编辑/创建表单(设置).因此我创建了SettingsController.

路线:

resources :settings, :only => :index do
  member do
    get 'cs_edit'
    put 'cs_update'
    post 'cs_create'
    delete 'cs_destroy'
  end
end
Run Code Online (Sandbox Code Playgroud)

控制器:

class SettingsController < ApplicationController
  before_filter :authenticate
...
def cs_create
  @cs = CaseStatus.find(params[:id])
  @cs.save

  redirect_to settings_path, :notice => 'Case Status was created successfully'
end
Run Code Online (Sandbox Code Playgroud)

视图部分:

<%= form_for(@cs, :url => url_for(:action => 'cs_create', :controller => 'settings'), :class => 'status_form') do |cs_f| %>
Run Code Online (Sandbox Code Playgroud)

问题是我收到以下错误:

Showing /home/michael/public_html/development/fbtracker/app/views/settings/index.html.erb where line #98 raised:

No route matches {:action=>"cs_create", :controller=>"settings"}
Extracted source (around line #98):

95:                   <% end %>
96:                 </table>
97: 
98:                 <%= form_for(@cs, :url => url_for(:action => 'cs_create', :controller => 'settings'), :class => 'status_form') do |cs_f| %>
99:                   <%= cs_f.text_field :name, :class => 'sname' %>
100:                  <%= cs_f.text_field :owt, :class => 'owt' %>
101:                  <%= cs_f.submit 'Add' %>
Run Code Online (Sandbox Code Playgroud)

我也检查了路线:

$ rake routes
...
cs_edit_setting GET    /settings/:id/cs_edit(.:format)             {:action=>"cs_edit", :controller=>"settings"}
cs_update_setting PUT    /settings/:id/cs_update(.:format)           {:action=>"cs_update", :controller=>"settings"}
cs_create_setting POST   /settings/:id/cs_create(.:format)           {:action=>"cs_create", :controller=>"settings"}
cs_destroy_setting DELETE /settings/:id/cs_destroy(.:format)          {:action=>"cs_destroy", :controller=>"settings"}
settings GET    /settings(.:format)                         {:action=>"index", :controller=>"settings"}
Run Code Online (Sandbox Code Playgroud)

如您所见,路由匹配{:action =>"cs_create",:controller =>"settings"}存在.但是url_for无法找到这条路线.为什么?

tar*_*ate 5

您已将 cs_create 定义为成员方法,但您的 url_for 调用没有给它一个对象。如果你确实想使用url_for这种方式,你可以这样做:

url_for(:id => @cs.id, :action => 'cs_create', :controller => 'settings')
Run Code Online (Sandbox Code Playgroud)

或者将其设为收集方法:

resources :settings, :only => :index do
  post 'cs_create', :on => :collection
  member do
    get 'cs_edit'
    put 'cs_update'
    delete 'cs_destroy'
  end
end
Run Code Online (Sandbox Code Playgroud)

然而,正如评论中提到的,这基本上忽略了 Rails 提供的所有支持,使这变得容易。我建议:

  • 为 CaseStatus 定义一个资源路由,它可以使用所有标准 RESTful 路由(这并不意味着您不能使所有这些设置在 /settings 下的单个页面上可见)
  • 使用标准 url 助手代替 url_for
  • 了解您不需要为所有 HTTP 操作使用单独的路径(例如,显示、更新和删除通常共享相同的路径,但具有不同的 HTTP 操作)