问题描述
我已经在堆栈溢出和Google上搜索失败了.
I have searched on stack overflow and google to no avail.
我有一个拥有下一个亲戚的人
I have a person who has_one next_of_kin
我可以创建一个嵌套形式(带有茧)的人,并且可以完美保存.由于某种原因,当我随后进入编辑页面时,它将删除关联的next_of_kin记录.它会渲染填充有记录数据的字段,但是数据库中的实际记录将被删除.
I can create a person with a nested form (with cocoon) and it saves perfectly. For some reason when I then go to the edit page it deletes the associated next_of_kin record. It renders the fields populated with the record's data, but the actual record in the database gets deleted.
我的表格
.full-width-row
= simple_form_for @person, url: {action: action}, wrapper: 'two_column_form' do |f|
.columns.medium-4
h4 = heading
.columns.medium-8
= f.button :submit, 'Save', class: 'right button tiny radius'
.columns.medium-12
.row
.medium-8.columns
= f.input :first_name
= f.input :last_name
= f.input :email
br
h6 Next of Kin
br
= f.simple_fields_for :next_of_kin do |nok|
= render 'next_of_kin_fields', f: nok
.link
= link_to_add_association "Add Next of Kin", f, :next_of_kin, class: 'button secondary tiny next_of_kin_button'
hr
我的_next_of_kin_fields部分
My _next_of_kin_fields partial
.nested-fields
= f.input :first_name
= f.input :last_name
= f.input :relationship, as: :select, collection: NextOfKin::RELATIONSHIP
= f.input :telephone
= link_to_remove_association "Remove next of kin", f, class: 'remove-association button tiny alert'
我的人模型:
class Person < ActiveRecord::Base
has_one :next_of_kin, dependent: :destroy
accepts_nested_attributes_for :next_of_kin, allow_destroy: true
end
我的Next_of_kin模型:
My Next_of_kin model:
class NextOfKin < ActiveRecord::Base
belongs_to :person
RELATIONSHIP = [ "Mother", "Father", "Brother", "Sister", "Aunt", "Uncle", "Spouse", "Other"]
end
当我访问编辑页面时,如何阻止它删除next_of_kin记录?
How do I stop it from deleting the next_of_kin record when I visit the edit page?
推荐答案
将link_to_add_association
中的force_non_association_create
设置为true
以避免这种情况
set force_non_association_create
in link_to_add_association
to true
to avoid this
= link_to_add_association "Add Next of Kin", f, :next_of_kin, force_non_association_create: true, class: 'button secondary tiny next_of_kin_button'
该参数的Cocoon文档: https://github.com/nathanvda/cocoon#force_non_association_create
Cocoon's documentation for this parameter: https://github.com/nathanvda/cocoon#force_non_association_create
这篇关于茧和has_one关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!