Reputation: 1792
I use Mogoid first time (current beta with Rails-API 4 support). I use it to preserve user forms as one document with embedded documents. In update method in controllers I use this construct to create new card if returned card don't have id
params[:form_cards].andand.each do |card|
card['form_card_fields'].andand.each do |field|
if !field['id'].blank?
@[email protected]_card_fields.find(field['id'])
else
@[email protected]_card_fields.create!
end
end
if @form.save
render json: @form, status: :created, location: @form
else
render json: @form.errors, status: :unprocessable_entity
end
It works in most cases. Unfortunatelly, sometimes something wrong happend and my created embedded document don't have persistent id, whenever I read it, result is different. After using
Example returned ID (each one is from different read operation for the same field)
536615c94d6163d0010a0000
536615d64d6163d0010b0000
536615dd4d6163d0010c0000
536615e84d6163d0010d0000
536616014d6163d0010e0000
My models looks like that:
class Form
include Mongoid::Document
include Mongoid::Timestamps
embeds_many :form_cards
end
class FormCard
include Mongoid::Document
include Mongoid::Timestamps
embeds_many :form_card_fields
embedded_in :form
end
class FormCardField
include Mongoid::Document
include Mongoid::Timestamps
embedded_in :form_card
end
I suppose it is some kind of persistence error but I can't find root cause...
I would be glad if whoever can help me cause it bugs me for three days
Upvotes: 1
Views: 352
Reputation: 8055
add cascade_callbacks: true
after the embeds_many
or embeds_one
so the models should look like the following
class Form
...
embeds_many :form_cards, cascade_callbacks: true
...
end
class FormCard
...
embeds_many :form_card_fields, cascade_callbacks: true
...
end
the cascade_callbacks
allow running the callbacks of the embedded docs... so that persisting a parent persists it's embedded docs.
Upvotes: 1