Home > Back-end >  In Rails, how can I detect if a model is being changed via nested attributes vs. on its own?
In Rails, how can I detect if a model is being changed via nested attributes vs. on its own?

Time:06-17

Let's say I have a model Checklist that has_many :items and accepts_nested_attributes_for :items.

I want to know in some Item callbacks and validations if it is being updated via nested attributes or just on its own. (This can e.g. let me optimise by running certain hooks only once when multiple Items are edited via the Checklist.)

How can I detect this?

CodePudding user response:

I found what seems like a pretty good way.

I add a flag to Item, and override Checklist items_attributes= to set that flag.

Item:

class Item < ApplicationRecord
  # …

  attr_accessor :updated_via_checklist

  after_save do
    if updated_via_checklist
      # Do nothing. The Checklist does something in batch.
    else
      do_something_for_just_this_item
    end
  end
end

Checklist:

class Checklist < ApplicationRecord
  # …

  after_save do
    do_something_in_batch(items)
  end

  def items_attributes=(value)
    return_value = super
    items.each { _1.updated_via_checklist = true }
    return_value
  end
end

CodePudding user response:

You can detect if an object is being updated via nested attributes by checking the object's _nested_attributes flag

https://guides.rubyonrails.org/v6.1/2_3_release_notes.html#nested-attributes

  • Related