[英]Check for an added association on 'create' and 'update' - Active Record
I'm trying to use an AR callback (after_save) to check, if an association was added on the latest 'update' or 'create'. 我正在尝试使用AR回调(after_save)来检查是否在最新的“更新”或“创建”上添加了关联。 However, I can't seem to find the correct way to do it.
但是,我似乎找不到正确的方法。
class Submission < ActiveRecord
has_many :notes, inverse_of: :submission, dependent: :destroy
accepts_nested_attributes_for :notes, :reject_if => proc { |attributes| attributes['message'].blank? }, allow_destroy: true
end
Here is my after_save 这是我的after_save
after_save :build_conversation
in that method I want to see, if a new note table was added on update or create... 我想用这种方法查看是否在更新或创建时添加了新的注释表...
def build_conversation
if self.notes.any?
binding.pry
end
end
This logic does not make sense, because if notes can exist, which is fine. 这种逻辑没有意义,因为如果可以存在注释,那很好。 Nevertheless, I only want to enter this block, if there is a new note added on update or create...
不过,如果在更新或创建中添加了新的注释,我只想输入此块。
Check out this post . 看看这个帖子 。 Basically, you add
include ActiveModel::Dirty
in the model, then in the after_change
callback you check if_notes_changed
. 基本上,您在模型中添加
include ActiveModel::Dirty
,然后在after_change
回调中检查if_notes_changed
。 This method is defined using method_missing
so for example if you have a name
column you can use if_name_changed
and so on. 此方法是使用
method_missing
定义的,因此例如,如果您有name
列,则可以使用if_name_changed
等。 If you need to compare the old vs new values, you can use previous_changes . 如果您需要比较旧值和新值,则可以使用previous_changes 。
Alternatively, you can use around_save
like so: 另外,您可以像这样使用
around_save
:
around_save :build_conversation
def build_conversation
old_notes = notes.to_a # the self in self.notes is unnecessary
yield # important - runs the save
new_notes = notes.to_a
# binding.pry
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.