简体   繁体   English

Rails嵌套表单:如何从子表单更新父属性

[英]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. 我有一个Contract模型父母,有一个Job Contract模型孩子。 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. Contract表类似于基础表, Job Contract表是该基础合同的详细信息,可以在以后进行扩展。

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 我想从子Job Contract表单中更新父Contract ,所以我在Job Contract表单中使用嵌套属性

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. 但是,这将在每次提交Job Contract表格时创建一个新Contract 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 我目前的计划是只使用一个Ajax按钮来更新ContractJob Contract形式

In the end, I didn't use nesting nor Ajax. 最后,我没有使用嵌套或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 我只是使用attr_accessor将所有内容放入“ Job Contract表单中,然后在孩子的更新操作中更新“ Contract父对象

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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