Model callbacks not working

Hello all,

I have a model named Ticket and two callback methods as def change_state and def change_country. Inside those methods below mentioned code was there

def change_state
  if self.changes.keys.includes?('state_id')
    # perform some actions
  end
end

def change_country
  if self.changes.keys.includes?('country_id')
    # perform some actions
  end
end

Update query:

ticket.update(state_id: 1, country_id: 2)

But if I change the ticket object of both state_id and country_id values, change_state method once executing properly. I haven’t received any self.changes.keys in change_country method.

Can anyone help me to resolve this? Thanks in advance :pray:

That depends on which callback you are using. A before_save, before_update should work, but the after_save, after_update don’t think so

1 Like

This kind of code sure seems to work for me. The puts lines run specifically when state or country (or both) are changed.

  before_update :change_state, :change_country

  def change_state
    if state_changed?
      # perform some actions
      puts 'STATE!'
    end
  end

  def change_country
    if country_changed?
      # perform some actions
      puts 'COUNTRY!'
    end
  end

As @brenogazzola had said, before_save and before_update will work fine, as well as an around_save which is a little fancier, allowing you to do things both before and after the actual database change if you wish.

1 Like