For example, I have three model classes:
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
I want to insert. For example here is my code:
Promotion.create(id: 999)
promotion.promotion_sets
.create(prepare_promotion_set_attrs(attributes['promotion_sets']))
Then those are methods for preparing children attributes:
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
This insert is successfully execute. But when I move insert code from inserting outside to accepts_nested_attributes_for
for only class Promotion:
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']))
I meet exception:
ActiveRecord::RecordNotFound: Couldn't find PromotionSet with ID=123456 for Promotion with ID=999
I cannot explain why. And I don't know why this is just only happen for class Promotion but class PromotionSet can insert using accepts_nested_attributes_for
without any error.