Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if an attribute changed after commit in Rails

I know that using dirty or changed? is useful in a before_commit situation or before the model is saved. After the model is saved, previous_changes gives the changes. Which is great. But,

How can I check if a specific attribute was changed in a controller if it looks like

def update
 @item = Item.find(params[:id])
if @item.update_attributes(item_params)
 # horray
 # check if the :name changed, if so do something about it
else
 # d'oh
end
end

Is there a better way than doing [email protected]_changes[:name].nil?

like image 503
Nick Ginanto Avatar asked Apr 25 '15 12:04

Nick Ginanto


1 Answers

I do not know if there is any better way, but I would do:

if @item.previous_changes.has_key?('name')
  # Name has been changed.
end
like image 139
Sharvy Ahmed Avatar answered Oct 05 '22 02:10

Sharvy Ahmed