简体   繁体   中英

Rails nested forms: How to update the parent attributes from a child form

I have a Contract model parent that has a Job Contract model child. The Contract table is like the base table and the Job Contract table is the details of that base contract that can be expanded in the future.

class Contract < ApplicationRecord
 has_one :job_contract, dependent: :nullify
 after_create :create_job_application_contract

 def create_job_application_contract
  JobContract.create(contract_id: self.id)
 end
end

class JobContract < ApplicationRecord
  belongs_to :contract, optional: true
end

I want to update the parent Contract from the child Job Contract form so I use nested attributes in the Job Contract form

class JobContract < ApplicationRecord
 belongs_to :contract, optional: true
 accepts_nested_attributes_for :contract
end

# edit.html.slim
= simple_form_for @job_contract do |f|
  = f.simple_fields_for :contract do |c|
   = c.input :salary

However, this creates a new Contract with every submission of the Job Contract form. Can I use nested attributes from the child to modify the parent? My current plan is to just use an ajax button to update the Contract from the Job Contract form

In the end, I didn't use nesting nor Ajax.

I just put everything in the Job Contract form by using attr_accessor then update the Contract parent in the child's update action

class JobContract < ApplicationRecord
 belongs_to :contract, optional: true
 attr_accessor :salary
end

# edit.html.slim
= simple_form_for @job_contract do |f|
  = f.input :salary

# job_contract_controller
if @job_contract.update(job_contract_params)
  @contract.update(contract_value: @job_contract.salary)
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM