I am trying to send a notification email in my rails app only if the value of my column status was modified by the current update. I tried using Active Model Dirty as was suggested in some post and the status_changed?
method. Unfortunately my email is never sent because @partnership.status_changed? constantly returns false even though the value of status was indeed changed during the last update. Here's my controller code :
def update
authorize @partnership
if @partnership.update(partnership_params)
send_notification_email
render json: {success: "partnership successfully updated"}, status: 200
else
render_error(nil, @partnership)
end
end
private
def send_notification_email
PartnershipMailer.partnership_status_change(@partnership).deliver_now if @partnership.status_changed?
end
I have also included Active Model Dirty in my model :
class Partnership < ActiveRecord::Base
include ActiveModel::Dirty
What am I doing wrong ?
.update
also saves the model after updating it's data, therefore resetting the dirty-values. Try using .assign_attributes
. It will just assign the attributes, then you can check for changes, and finally remember to save the model.