1
第一次我使用STI,并且在尝试将accepts_nested_attributes_for
与嵌套的继承对象一起使用时遇到问题。验证使用accept_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
我在做什么错在这里?
UPDATE:
这似乎与导轨5和协会有required: true
默认的问题。当在Invoice
模型上关闭required: true
并设置foreign_key
时,它会正确分配父模型ID并保存父模型和子模型。
一个念头:也许是协会应在父类中声明,而不是即不PackageItem属于包,而是DocumentItem属于文档 – henrebotha
@henrebotha相当肯定,将工作会。错过了使用STI想法的地方:/ –