使用 assign_attributes 销毁父级保存的深层关联对象

Destroy deep associated object on parent save, using assign_attributes

我想删除 assign_attributes.

中的一条深层关联记录

Screen 是我唯一需要保存的对象,但是如果 params[:delete]true 对于那个特定的 NoteMember 对象。

以下是 table 结构:

型号

class Screen < ActiveRecord::Base
  has_many :alerts

  accepts_nested_attributes_for :alerts
end

class Alert < ActiveRecord::Base
  has_many :notes

  accepts_nested_attributes_for :notes
end

class Note < ActiveRecord::Base
  has_many :note_members

  accepts_nested_attributes_for :note_members
end

class NoteMember < ActiveRecord::Base
end

控制器

s = Screen.where(id: <some_id>).first

alert_attrs = []

params[:alerts].each do |a|
  notes_attrs = []

  params[:notes].each do |n|
    note_member_attrs = []

    params[:note_members].each do |nm|
      # if nm[:delete] = true, I need to delete the note member on saving Screen object
      note_member_attrs.push({
        id: nm[:id],
        visibility: nm[:visibility]
      })
    end

    notes_attrs.push({
      id: n[:id],
      description: n[:description],
      note_members_attributes: note_member_attrs
    })
  end

  alert_attrs.push({
    id: a[:id],
    name: a[:name]
    notes_attributes: notes_attrs
  })
end

s.assign_attributes(
  alerts_attributes: alert_attrs
)

s.save!

如何实现?

您可以使用 rails 内置销毁功能:

accepts_nested_attributes_for :note_members, allow_destroy: true

并通过

note_members_attributes: [ { _destroy: true, id: 123 }]

note_members 个需要删除。