我第一次使用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_name
和belongs_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并保存父模型和子模型。