我有模型 Item 和 ItemCategory。项目所属_到项目类别。
在 Item 表单上,我希望能够创建一个新的 ItemCategory 并将其分配给当前项目。
所以我在项目表单上添加了:
<%= link_to '+', new_quick_category_path(item_id: @item.id), remote: true %>
然后在 items_controller 上:
def new_quick_category
@item_category = ItemCategory.new
@item = Item.find(params[:item_id])
end
然后我得到了表格:
<%= simple_form_for (@item_category), html: { id: :item_category}, remote: true do |f| %>
<%= f.error_notification %>
<%= f.error_notification message: f.object.errors[:base].to_sentence if f.object.errors[:base].present? %>
<h5> Name </h5>
<%= f.input :name, label: false %>
<%= f.button :submit, "Create", class: "btn btn-sm btn-success" %>
<% end %>
现在用新创建的 item_category 更新当前项目,我假设我需要在 item_categories_controller 上做:
def create
@item = Item.find(params[:item_id])
@item.update_attributes(item_category_id: @item_category.id)
....
end
所以我需要传递参数 item_id 来在 item_categories_controller 上创建操作。
我想到的一个解决方案是将它传递给表单上的创建按钮,例如:
<%= f.button :submit, "Create"(item_id: @item.id), class: "btn btn-sm btn-success" %>
但它不起作用。
我该怎么做?或者我应该创建一个嵌套表单?
请尝试将项目设置为表单中的隐藏字段,以便在您提交表单时将其发送到控制器,隐藏字段应该从这样的参数中获取值
<%= hidden_field_tag :item_id, params[:item_id] %>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句