例如,我有三个模型类:
class Promotion < ApplicationRecord
has_many :promotion_sets, dependent: :destroy
accepts_nested_attributes_for :promotion_sets
end
class PromotionSet < ApplicationRecord
belongs_to :promotion
has_many :promotion_set_details, dependent: :destroy
accepts_nested_attributes_for :promotion_set_details
end
class PromotionSetDetail < ApplicationRecord
belongs_to :promotion_set
end
我想插入。例如这里是我的代码:
Promotion.create(id: 999)
promotion.promotion_sets
.create(prepare_promotion_set_attrs(attributes['promotion_sets']))
然后这些是准备子属性的方法:
def prepare_promotion_set_attrs(set_attrs)
promotion_sets_attributes = []
set_attrs&.each do |attr|
promotion_sets_attributes.push(
id: 123456,
promotion_set_details_attributes: prepare_promotion_set_details_attrs(attr['set_details'])
)
end
promotion_sets_attributes
end
def prepare_promotion_set_details_attrs(set_detail_attrs)
promotion_set_details_attributes = []
set_detail_attrs&.each do |attr|
promotion_set_details_attributes.push(
# sample fields here
)
end
此插入已成功执行。但是当我将插入代码从插入外部移动到accepts_nested_attributes_for
仅用于类促销时:
Promotion.create(
id: 999,
promotion_sets_attributes: prepare_promotion_set_attrs(some_data),
)
# not use this
# promotion.promotion_sets
# .create(prepare_promotion_set_attrs(attributes['promotion_sets']))
我遇到异常:
ActiveRecord::RecordNotFound: 找不到 ID=123456 的 PromotionSet 用于 ID=999 的 Promotion
我无法解释为什么。而且我不知道为什么这只发生在Promotion类但PromotionSet类可以插入使用accepts_nested_attributes_for
而没有任何错误。