【发布时间】:2017-05-17 20:30:51
【问题描述】:
我正在运行带有以下信息的 Rails 5.1 应用程序:
型号
class Company < ApplicationRecord
has_many :complaints
accepts_nested_attributes_for :complaints
validates :name, presence: true
end
class Complaint < ApplicationRecord
belongs_to :company
validates :username, :priority, presence: true
end
控制器
class ComplaintController < ApplicationController
def new
@company = Company.new
@company.complaints.build
end
def create
@company = Company.new(company_params)
respond_to do |format|
if @company.save
format.html { redirect_to complaint_url }
else
format.html { render :new }
end
end
end
private
def company_params
params.require(:company).permit(:name, complaints_attributes: [:username, :priority])
end
视图中的表单
<%= form_for @company do |f| %>
<%= f.label :name, "Company" %>
<%= f.text_field :name, type: "text" %>
<%= f.fields_for :complaints do |complaint| %>
<%= complaint.label :username, "Username" %>
<%= complaint.text_field :username %>
<%= complaint.label :priority, "Priority" %>
<%= complaint.text_field :priority %>
<% end %>
<%= f.submit 'Submit' %>
<% end %>
如果我只有一个输入字段用于表单的complaint_attributes 部分(换句话说,只有一个用户名字段和一个优先级字段,如上所示),这很好。
但是,如果我想在表单中有多个用户名/优先级字段,以便我可以在一次提交中提交多个用户名/优先级组合,我发现提交表单只会保存最后一个用户名/优先级值从表格。这种观点的例子是:
<%= form_for @company do |f| %>
<%= f.label :name, "Company" %>
<%= f.text_field :name, type: "text" %>
<%= f.fields_for :complaints do |complaint| %>
<div>
<%= complaint.label :username, "Username" %>
<%= complaint.text_field :username %>
<%= complaint.label :priority, "Priority" %>
<%= complaint.text_field :priority %>
</div>
<div>
<%= complaint.label :username, "Username" %>
<%= complaint.text_field :username %>
<%= complaint.label :priority, "Priority" %>
<%= complaint.text_field :priority %>
</div>
<% end %>
<%= f.submit 'Submit' %>
<% end %>
我注意到在提交表单时,我得到了这样的哈希(用于提交单个投诉):
{"utf8"=>"✓", "authenticity_token"=>"...", "company"=>{"name"=>"Test", "complaints_attributes"=>{"0"=>{"username"=>"test_person", "priority"=>"1"}}}, "commit"=>"Submit"}
有没有办法修改参数使其与此类似并将其保存到数据库中?:
{"utf8"=>"✓", "authenticity_token"=>"...", "company"=>{"name"=>"Test", "complaints_attributes"=>{"0"=>{"username"=>"test_person", "priority"=>"1"}"1"=>{"username"=>"test_person", "priority"=>"2"}}}, "commit"=>"Submit"}
如果不是上述情况,如果在一个表单中为用户名/优先级值使用多个字段,那么保存用户名/优先级值的最佳方法是什么?
编辑:我应该指出,我可以根据需要动态添加用户名/优先级字段组,所以我不想被限制在一个设定的数字。
【问题讨论】:
-
仅供参考,您的
EDIT使它成为一个完全不同的问题...... -
是的 - 我很抱歉没有指出这一点。第一个答案发布后我就意识到了。
标签: ruby-on-rails forms