Trigger a before_create before a before_save

Viewed 383

In the ActiveRecord callback chain, a before_save is triggered before a before_create:

before_validation 
after_validation 
before_save 
around_save 
before_create 
around_create 
after_create 
after_save 
after_commit/after_rollback

The problem is I have a before_create which sets a reference_number. And I have a before_save which checks for changed attributes and works on changed attributes. Since the before_create is called after the before_save, that reference_number is not considered a changed attribute and therefore I am unable to work on it:

before_create :set_reference_number
before_save :set_denormalized_fields

def set_reference_number
   prefix = determine_type ? 'CO' : 'CA'
   self.reference_number = "#{prefix}-#{1}"
end

def set_denormalized_fields
  if changes.any?
    handle_changed_attributes changes
  end
end

How can I change the callback chain to ensure that reference_number is a changed attribute when I call set_denormalized_fields?

1 Answers

You could add a condition like if changes.any? || new_record? but you need to be sure the attribute is actually set.

Related