Cocoon和has_one协会

时间:2014-09-16 14:06:10

标签: ruby-on-rails forms cocoon-gem

我搜索了堆栈溢出并谷歌无济于事。

我有一个人__ next_of_kin

我可以创建一个具有嵌套形式(带有茧)的人,它可以完美地保存。出于某种原因,当我转到编辑页面时,它会删除关联的next_of_kin记录。它使用记录的数据呈现填充的字段,但数据库中的实际记录将被删除。

我的表格

.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部分

.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模型:

class NextOfKin < ActiveRecord::Base
  belongs_to :person
  RELATIONSHIP = [ "Mother", "Father", "Brother", "Sister", "Aunt", "Uncle", "Spouse", "Other"]
end

当我访问编辑页面时,如何阻止它删除next_of_kin记录?

1 个答案:

答案 0 :(得分:2)

force_non_association_create中的link_to_add_association设置为true以避免此

= 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