Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting if value of attribute changed during last update doesnt work with Active Model Dirty

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 ?

like image 732
David Geismar Avatar asked Aug 30 '16 18:08

David Geismar


1 Answers

.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.

like image 53
ollpu Avatar answered Sep 26 '22 14:09

ollpu