将Accept_nested_attributes_for与单表继承一起使用时验证失败

时间:2017-01-21 19:33:05

标签: ruby-on-rails ruby activerecord ruby-on-rails-5 single-table-inheritance

我第一次使用STI时,在尝试将accepts_nested_attributes_for与嵌套的继承对象一起使用时,我遇到了问题。

class Document < ApplicationRecord
  # code removed for brevity
end

class DocumentItem < ApplicationRecord
   # code removed for brevity
end

class Package < Document
    belongs_to :user
    validates :title, :user, presence: true

    has_many :package_items, dependent: :destroy
    accepts_nested_attributes_for :package_items, reject_if: :all_blank, allow_destroy: true
end

class PackageItem < DocumentItem
    belongs_to :package
end

当我尝试使用嵌套属性时,事情就会停止工作:

Package.create!(title: 'test', 
                user: User.last, 
                package_items_attributes: [{title: 'test'}])

导致以下错误:

ActiveRecord::RecordInvalid: Validation failed: Package items package must exist

我已尝试在foreign_key关系中设置class_namebelongs_to,但没有运气:

class PackageItem < DocumentItem
    belongs_to :package, foreign_key: 'document_id', class_name: 'Document'
end

我在这里做错了什么?

更新:

这似乎是Rails 5和默认情况下required: true的关联的问题。关闭required: true并在foreign_key模型上设置Invoice时,它会正确分配父模型ID并保存父模型和子模型。

1 个答案:

答案 0 :(得分:2)

原来它与STI无关,并且是已知的Rails 5错误。 :(

https://github.com/rails/rails/issues/25198