创建一个父对象,其HABTM accepted_nested_attributes_for children忽略了关联(子)属性更新

时间:2016-11-10 14:00:42

标签: ruby-on-rails ruby-on-rails-4 has-and-belongs-to-many cocoon-gem

我的ActiveRecord模型:

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

父母创建的控制器。 [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]

父母的简单形式:

= f.simple_fields_for :children, @children do |child|
   = render 'child_fields', f: child

子字段文件:

= f.hidden_field :id, value: f.object.id
= f.hidden_field :user_id, value: f.object.user_id
...

[/ EDITED]

重点是,当保存Parent时,children_parents连接表更新(很好),子表没有插入id子项(很好),但是如果子项已经有ID(持久化),子表是不对它们执行更新

调试@parent.save之前的prev行,可以确保@parent.children包含子属新属性。已执行命令@parent.save,子属性未更新,但如果再次调用save,则会执行子更新。

可能会发生什么?

0 个答案:

没有答案