Bitwise
Bitwise

Reputation: 8461

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'. 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 :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...

Upvotes: 0

Views: 688

Answers (1)

max pleaner
max pleaner

Reputation: 26758

Check out this post. Basically, you add include ActiveModel::Dirty in the model, then in the after_change callback you check 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. If you need to compare the old vs new values, you can use previous_changes.

Alternatively, you can use around_save like so:

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

Upvotes: 1

Related Questions