I'm working on a form object where I build and save an instance of Service, but I'm having a hard time building and saving nested records.
A Service has_one features_set and accepts_nested_attributes_for for it.
A FeaturesSet accepts_nested_attributes_for :crown_items, which is a join table between that model and Crown.
features_set.rb
class FeaturesSet < ApplicationRecord
has_many :crown_items
has_many :crowns, through: :crown_items
accepts_nested_attributes_for :crown_items
end
crown_item.rb
class CrownItem < ApplicationRecord
belongs_to :features_set
belongs_to :crown
end
crown.rb
class Crown < ApplicationRecord
has_many :crown_items
has_many :features_sets, :through => :crown_items
end
This is what my ServiceForm form object looks like:
class ServiceForm
include ActiveModel::Model
include ActiveModel::Validations::Callbacks
attr_accessor :crowns
before_validation :build_features_set
def initialize(params = {})
super(params)
end
def save
return false if invalid?
service.save
end
def service
@service ||= Service.new
end
def build_features_set
service.build_features_set(
crown_items_attributes: crowns
)
end
end
On initialization, this is what the crowns param looks like:
{0=>{:quantity=>1, :crown_id=>1}, 1=>{:quantity=>5, :crown_id=>2}}
When I try to save the service instance, I get the following error:
Couldn't find CrownItem with ID=1 for FeaturesSet with ID=
and now if I access the crowns params again, it looks like this:
{0=>{:quantity=>1, :crown_id=>1, "id"=>"1"}, 1=>{:quantity=>5, :crown_id=>2, "id"=>"1"}}
It looks like it is creating the crown_item records as it's adding an ID to them (albeit they both have the same ID), but I don't really understand what the error is telling me.