【问题标题】:why form_for rails is generating action: 'show'?为什么 form_for rails 正在生成动作:'show'?
【发布时间】:2017-10-20 16:23:09
【问题描述】:

我在 Rails 中使用form_for 生成一个表单,如下所示:

# Controller
def new
  @species = Specie.new
  render partial: 'maintainers/species/new'
end

# In _new.html.erb
<%= render 'maintainers/species/form', species: @species %>

# In maintainers/species/form
<%= form_for(species, html: {remote: true, id: 'species_form'}) do |f| %>
...
<% end %>

但我收到此错误:

No route matches {:action=&gt;"show", :controller=&gt;"species"} missing required keys: [:id]

会发生什么?

【问题讨论】:

  • 点击提交后会出现这种情况吗?
  • 不,这发生在部分充电,创建表单时。
  • 您的代码中有错字:@species = Specie.new 应该是 @species = Species.new。不知道是不是这个问题。
  • 实例化 Species 时不会生成 id。那是你的问题
  • @TomAranda 我已经用 Scaffold 生成了这个,并且 Specie 对象在其他地方工作正常。

标签: ruby-on-rails form-for


【解决方案1】:

您需要发出 POST 请求来调用创建操作:

# In maintainers/species/form
<%= form_for(species, html: {remote: true, , method: :post, id: 'species_form'}) do |f| %>
...
<% end %>

注意method: :post 参数。

默认情况下,form_for 会发出一个 GET 请求,映射到 Rails 中的显示动作。

【讨论】:

  • 这应该是一个解决方案,但是form_for会根据传递的对象自动生成'method',这种情况下会生成'POST'方法,导致对象只是初始化,另一种情况是当对象有一个像 Object.find(1) 这样的记录时,在编辑操作中使用了什么并生成了“PATCH”方法。现在,我在这两种情况下都使用此表单部分并给我带来问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-20
  • 1970-01-01
  • 2013-06-15
  • 1970-01-01
相关资源
最近更新 更多