Lovish Choudhary
Lovish Choudhary

Reputation: 167

Accessing before update value of active record object

I have implemented a function which is called when an active record object is successfully updated, but I have to pass the before and after update value of a active record value to that function. I am trying to implement is in the following way, but the value that is getting passed is only the updated value.

def update
 lead_before_update = @old_car_lead

 respond_to do |format|
  if @old_car_lead.update(old_car_lead_params)
    format.html { redirect_to @old_car_lead, notice: 'Lead was successfully updated.' }
    format.json { render :show, status: :ok, location: @old_car_lead }
    lead_after_update = @old_car_lead

    Lead.send_lead(lead_before_update, lead_after_update)

  else
    format.html { render :edit }
    format.json { render json: @old_car_lead.errors, status: :unprocessable_entity }
  end
end

end

When I try to log the vale of lead_before_update and lead_after_update, I observe both have the same value.

Can anyone please tell how to pass both the before update and after update value to the function.

Upvotes: 0

Views: 1710

Answers (1)

Awlad Liton
Awlad Liton

Reputation: 9351

lead_before_update and lead_after_update both are pointing same object( old_car_lead). When it changes it changes all.

Two ways around here:

  1. You should duplicate the object and assign to a variable.

    lead_before_update = @old_car_lead.dup lead_after_update = @old_car_lead.dup

  2. You can use @old_car_lead.attribute_name_was it will give you the previous value of the attribute_name

reference for second option: What is the ActiveModel method attribute "_was" used for?

Upvotes: 1

Related Questions