我必须在一个页面(设置)上为多个表格编辑/创建表单。因此我创建了SettingsController。
路线:
resources :settings, :only => :index do
member do
get 'cs_edit'
put 'cs_update'
post 'cs_create'
delete 'cs_destroy'
end
end
控制器:
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
观点部分:
<%= form_for(@cs, :url => url_for(:action => 'cs_create', :controller => 'settings'), :class => 'status_form') do |cs_f| %>
问题是我收到以下错误:
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' %>
我也检查了路线:
$ 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"}
如您所见,路线匹配{:action =&gt;“cs_create”,:controller =&gt;“settings”}存在。但是url_for无法找到这条路线。为什么呢?
答案 0 :(得分:4)
您已将cs_create定义为成员方法,但您的url_for调用未向其提供对象。如果你真的想以这种方式使用url_for
,你可以这样做:
url_for(:id => @cs.id, :action => 'cs_create', :controller => 'settings')
或者将其作为收集方法:
resources :settings, :only => :index do
post 'cs_create', :on => :collection
member do
get 'cs_edit'
put 'cs_update'
delete 'cs_destroy'
end
end
然而,正如评论中所提到的,这基本上忽略了rails提供的所有支持,以简化这一过程。我建议: