My ActiveRecord Models:
class Parent < AR
has_and_belongs_to_many :children
accepts_nested_attributes_for :children, reject_if: :all_blank, allow_destroy: true
end
class Child < AR
has_and_belongs_to_many :parents
end
The controller for Parent creating. [EDITED]
def new
current_child = current_user.set_child #first or initialize
@parent = current_user.parents.build
@parent.child_ids = [current_child.id].compact
@children = [current_child]
end
def create
@parent = current_user.parents.build(parent_params)
if @parent.save
...
else
@children = @parent.children
render :new
end
end
[/EDITED]
def parent_params
params.require(:parent).merge( child_ids: params[:parent][:children_attributes].map{|p,v| v[:id]} ).
permit(:id, :picture, :remove_picture, child_ids: [],
children_attributes: [ :id, :user_id, :full_name, :_destroy ] )
end
[EDITED]
The simple form for parent:
= f.simple_fields_for :children, @children do |child|
= render 'child_fields', f: child
child fields file:
= f.hidden_field :id, value: f.object.id
= f.hidden_field :user_id, value: f.object.user_id
...
[/EDITED]
The point is that when Parent is saved, children_parents join table is update (nice), children table has no id children inserted (nice), BUT if the children already has an ID (persisted), children table does not perform the update on them
Debugging the prev line before @parent.save
, is possible to ensure that @parent.children
contains the children new attributes. Executed the command @parent.save
, children attributes aren't updating , but if save
is called again, it performs the children update.
What could be happening?