我有一个表格,其中包含2个专业的嵌套表格(证书和培训)。每个人在Professional模型中都有关联accepted_nested_attributes_for。我可以凭他的证书和培训创建一个新的专业人士。但是,当我保存时,不是更新证书和培训,而是创建一个新证书。
我的专业控制员:
def edit
@professional = Professional.find(params[:id])
@component = Component.all
cert = Certificate.where('professional_id = ?', params[:id])
cert.each do |certificate|
@certificate = certificate
end
tra = Training.where('professional_id = ?', params[:id])
tra.each do |training|
@training = training
end
@work = Work.all
@charge = Charge.all
@entities =Array.new
TypeEntity.where("id IN (1,5)").each do |tent|
@entities << tent.entities
end
@reg = Time.now.to_i.to_s
@major = Major.all
@action = 'edit'
render layout: false
end
def update
profesional = Professional.find(params[:id])
if profesional.update_attributes(professional_parameters)
flash[:notice] = "Se ha actualizado correctamente los datos."
redirect_to :action => :index
else
profesional.errors.messages.each do |attribute, error|
flash[:error] = flash[:error].to_s + error.to_s + " "
end
# Load new()
@profesional = profesional
render :edit, layout: false
end
end
private
def professional_parameters
params.require(:professional).permit(
:name,
:dni,
:professional_title_date,
{:major_ids => []},
:date_of_tuition,
:code_tuition,
:professional_title,
:tuition,
:cv,
certificates_attributes: [
:id,
:professional_id,
:work_id,
:charge_id,
:entity_id,
:num_days,
:start_date,
:finish_date,
{:component_work_ids => []},
:certificate,
:other,
:_destroy
],
trainings_attributes: [
:id,
:professional_id,
:type_training,
:name_training,
:num_hours,
:start_training,
:finish_training,
:training,
:_destroy
]
)
end
这是模特:
class Certificate < ActiveRecord::Base
has_one :charge
belongs_to :professional
end
class Professional < ActiveRecord::Base
has_and_belongs_to_many :majors
has_many :certificates
has_many :trainings
accepts_nested_attributes_for :certificates, :allow_destroy => true
accepts_nested_attributes_for :trainings, :allow_destroy => true
end
class Training < ActiveRecord::Base
belongs_to :professional
end
表单以此开头:
=simple_form_for([:biddings, @professional], html: { multipart: true }) do |f|
之后我在引导向导中有3个表单。
答案 0 :(得分:2)
确保ID
表单中的Hash
中包含Edit
个属性。
由于您的模型具有一对多,
For each hash that does not have an id key a new record will be instantiated, unless
the hash also contains a _destroy key that evaluates to true.