【问题标题】:Rails custom action missing required key errorRails 自定义操作缺少必需的键错误
【发布时间】:2016-11-04 11:45:45
【问题描述】:

show.html.erb

<h1><%= @script.Name %></h1>

<%= simple_form_for @script , :url => script_execute_path do |f| %>
  <%= f.input :mainDirectory %>
  <%= f.input :customFilePath %>
  <%= f.button :submit, 'Run' %>
<% end %>

routes.rb

  root :to => "scripts#index"
  resources :scripts do
    get "execute"
  end

型号

class AddNameToScript < ActiveRecord::Migration
  def change
    add_column :scripts, :Name, :string
    add_column :scripts, :Description, :text
  end
end

execute 是我添加的自定义操作,我想从 show 转到该操作。

routes.rb

...
    script_execute GET    /scripts/:script_id/execute(.:format) scripts#execute
...

但我收到一个错误

No route matches {:action=>"execute", :controller=>"scripts", :id=>"1"} 
missing required keys: [:script_id]

但是为什么我需要[:script_id]?这不是一个自定义操作,我可以定义我想要的方式吗?这里缺少什么以及如何传递[:script_id]

【问题讨论】:

  • 您能否将此命令的输出 - rake routes | grep execute - 添加到您的问题中?这将显示execute 方法期望的参数(如果有)。
  • @jeffdill2:现在

标签: ruby-on-rails routing routes rails-routing


【解决方案1】:

从路由器输出中可以看出,execute 需要一个 script_id 参数 (/scripts/:script_id/execute(.:format)。要消除这种期望,您需要在 collection 而不是 member 级别声明该路由。您可以通过以下两种方式之一执行此操作:

get :execute, on: :collection

或者,如果您想在集合中包含其他路线,您可以将其放入一个块中:

collection do
  get :execute
end

仅供参考,在此更改之后再次运行 rake routes | grep execute 以查看 URL 帮助程序的名称已更改为什么,以便您可以相应地更新您的视图。

干杯!


更新:

要回答 cmets 中的问题,如果您想传入 script_id 参数(或与此相关的任何参数),您可以通过将其声明为 URL 帮助程序的参数来实现。所以根据你目前的观点,它看起来像这样:

<h1><%= @script.Name %></h1>

<%= simple_form_for @script , :url => script_execute_path(script_id: @script.id) do |f| %>
  <%= f.input :mainDirectory %>
  <%= f.input :customFilePath %>
  <%= f.button :submit, 'Run' %>
<% end %>

但是,我想在这里指出更多的事情:

  1. 看来您打算更新Script 对象,所以我不确定您为什么要从show 视图创建execute 方法,而不是仅使用update 方法这已经可以通过resources :scriptsedit 视图中获得。
  2. 同样,您似乎打算根据您的视图 PUT 或 POST 某些内容,但您的 execute 路由被定义为 GET。不确定这是否是您想要的。

【讨论】:

  • 如果我需要 /scripts/:script_id/execute(.:format) 格式,那我该如何传递 id?
  • @InQusitive 一秒钟,我会更新我的答案来解决你的问题。
  • 很遗憾没有双重“喜欢”选项:)
  • 哈!我建议查看这些文档——guides.rubyonrails.org/routing.html。您很快就会成为路由专家。 :-)
【解决方案2】:

:id 传递给您的表单助手并尝试

<%= simple_form_for @script , :url => script_execute_path(@script) do |f| %>
  <%= f.input :mainDirectory %>
  <%= f.input :customFilePath %>
  <%= f.button :submit, 'Run' %>
<% end %>

【讨论】:

  • 这将通过id
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-18
  • 2014-11-20
相关资源
最近更新 更多