gpt4 book ai didi

ruby-on-rails - url_for 方法找不到路由

转载 作者:行者123 更新时间:2023-12-03 16:03:11 25 4
gpt4 key购买 nike

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

路线:

resources :settings, :only => :index do
member do
get 'cs_edit'
put 'cs_update'
post 'cs_create'
delete 'cs_destroy'
end
end

Controller :
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

View 部分:
<%= 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=>"cs_create", :controller=>"settings"} 存在。但是 url_for 找不到这条路线。为什么?

最佳答案

您已将 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 提供的所有支持,使这变得容易。我建议:
  • 为 CaseStatus 定义一个可以使用所有标准 RESTful 路由的资源路由(这并不意味着您不能在/settings
  • 下的单个页面上显示所有这些设置)
  • 使用标准的 url 助手代替 url_for
  • 了解您不需要所有 HTTP 操作的单独路径(例如,显示、更新和删除通常共享所有相同的路径,但具有不同的 HTTP 操作)
  • 关于ruby-on-rails - url_for 方法找不到路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7671898/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com