问题:可以正常新建 BpFeatureName 和 BpFeatureValue,但是在更新修改嵌套表单的时候,BpFeatureName 可以正常修改,但是嵌套的表 BpFeatureValue 会新增数据,代码如下:
BpFeatureName 和 BpFeatureValue 一对多关系,如下:
class BpFeatureName < ApplicationRecord
has_many :bp_feature_values, :dependent => :delete_all
belongs_to :user
accepts_nested_attributes_for :bp_feature_values
end
class BpFeatureValue < ApplicationRecord
belongs_to :bp_feature_name
end
new 和 edit 的 controller 如下
class BpFeatureNamesController < ApplicationController
def new
@bp_feature_name = BpFeatureName.new
@bp_feature_name.bp_feature_values.build
end
def create
@bp_feature_name = current_user.bp_feature_names.build(bp_feature_name_params)
if @bp_feature_name.save ...
end
end
def edit
@bp_feature_name = BpFeatureName.find(params[:id])
end
def update
if @bp_feature_name.update(bp_feature_name_params)
.....
end
end
def bp_feature_name_params
params.require(:bp_feature_name).permit(:name,:user_id, bp_feature_values_attributes: [:value])
end
end
new 和 edit 的_form 如下:
<%= form_with(model: bp_feature_name, local: true, class: "form form-horizontal") do |form| %>
<%= label_tag :name,'特征名', class:"col-sm-2 control-label" %>
<%= form.text_field :name , class: "form-control" %>
<%= form.label :value,'特征值', class:"col-sm-2 control-label" %>
<%= form.fields_for :bp_feature_values,@bp_feature_name.bp_feature_values do |bp_feature_values_form| %>
<%= bp_feature_values_form.text_field :value , class: "form-control"%>
<% end %>
<%= form.submit '创建', class:"btn btn-primary" %>
<%= link_to '返回', bp_feature_names_path ,class:"btn btn-default"%>
<% end %>