I have a model with an attribute car
I want to add a field car_created_at
that will have as a value the timestamp of the first time car
actually assigned a value.
What is the proper way to do that? maybe after_update
hook?
CodePudding user response:
According to the trusty rails docs, after_update
only runs on updates.
after_save
runs both when created and updated. So I would use that.
And beware that just doing save
in the hook will cause infinite call stack, meaning save
will trigger after_save
, in which save
is called.
So you will have to use update_columns
.
after_save :touch_car_created
def touch_car_created
if car_created_at.nil?
update_columns(car_created_at: Time.zone.now)
end
end
CodePudding user response:
I would prefer to go with before_save
because this callback get called before object creation and updation.
# This callback works only when car value has changed
# and car_created_at is nil.
before_save :assign_car_created_time, if: Proc.new { car_changed? && car_created_at.nil? }
private
# Keep it private so it won't be accessed publicly.
def assign_car_created_time
# We only need to assign the value
self.car_created_at = Time.zone.now
end
Hope this works for you.