Activerecord dirty check for either created or updated

Viewed 135

I have a ActiveRecord model say List with has a connected boolean flag?

I want a callback to check if the List is reconnected which can happen 2 ways

  • connected for the first time while created
  • disconnected and reconnected with a update

I want to use ActiveMecord::Dirty api to do the check..but i wonder if there is a better way?

I come across this situation a lot and was wondering if there is a API which gives me changes as [nil, true] on create for changes to connected flag.

I use this for calling a 3rd party so need it after commit.

# The first line in the code checks if list is created with connected true and
# the second line checks if list was updated from connected false to true.

def reconnected?
  return true if connected_previous_change.blank? && connected

  connected_previous_change == [false, true]
end
1 Answers

You could rewrite the callback as follows:

def reconnected?
  connected_previously_changed? && connected
end

connected_previously_changed? would return true when the connected attribute value was changed - Useful while checking in an after_commit callback. The change could be from nil to any value (true/false) and vice versa. This returns true even when the value changes from false to true and vice versa. So we'd need the second condition to check if the current value is true.

Refer: https://api.rubyonrails.org/classes/ActiveModel/Dirty.html

Related