ruby-on-rails - Cocoon 和 has_one 关联

标签 ruby-on-rails forms cocoon-gem

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

我有一个人有_one 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 记录?

最佳答案

套装force_non_association_createlink_to_add_associationtrue为了避免这种情况

= 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

关于ruby-on-rails - Cocoon 和 has_one 关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25870978/

相关文章:

javascript - 如何将 'attach' ASP.NET 字节数组转换为表单上的 'file' 类型输入字段?

ruby-on-rails - 如何使用 cocoon gem 处理 Rails 4 中嵌套表单的数据?

ruby-on-rails - Unicorn 和 omniauth-facebook - 未初始化的常量 OmniAuth

JavaScript 表单验证错误

jquery - 有_许多 :through nested_form that can build multiple instances

javascript - 将多个变量传递到 jquery 对话框表单

ruby-on-rails - Rails 4 & 茧 gem : Cannot add 3rd level child to dynamically added 2nd level child

ruby-on-rails - 如何处理 Rails 中的嵌套表单?

ruby-on-rails - 在 Rails 应用程序中获取 URLS 的完整列表

ruby-on-rails - Rails 3.2 - #<Array :. 的未定义方法 `where' .. - Model.where() 的查询