如何检查ActiveRecord的after_save回调中是否更改了关联的记录数组?

时间:2015-08-28 22:27:36

标签: ruby-on-rails activerecord rails-activerecord

我的代码如下:

   class MyModel < ActiveRecord::Base
     has_many :associated_records
     accepts_nested_attributes_for :associated_records

     after_save :send_notification, if: :relevant_data_changed?

     def relevant_data_changed?
       return self.some_column_changed? || self.associated_records.changed?
     end

     def send_notification
       # Do stuff
     end
   end

我知道我可以检查直接在模型上的列是否发生了变化(就像我在示例中所做的那样),我认为如果有has_one,我甚至可以检查单个嵌套对象是否发生了变化与该对象的关系(我相信通过self.nested_model.changed?),但我无法弄清楚如何检查对象数组是否已更改,例如我的示例中的associated_records

编辑:为了记录,我确实从这里尝试了建议的解决方案:Rails: if has_many relationship changed。但是,在仅添加或删除对象而不是实际更改对象的情况下,它不起作用。

有谁知道我可以这样做的方式?感谢。

2 个答案:

答案 0 :(得分:0)

这样的事情应该有效:

class MyModel < ActiveRecord::Base
  has_many :associated_records, after_save :force_save_associated_records      

  def force_save_associated_records
    associated_records.map{|x| x.save! if x.changed?}
  end
end

答案 1 :(得分:0)

因此,经过一番挖掘后,事实证明,我正在尝试做的正确方法是使用after_addafter_remove回调。

How can I validate that has_many relations are not changed

在我的例子中,它将类似于:

has_many :associated_records, after_add: :send_notification

# This gets called for every new record added, even if multiple are
# added at once
def send_notification(new_record)
  # Do stuff with the new_record
end