ruby-on-railsruby-on-rails-4activerecord

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 !@item.previous_changes[:name].nil?


Solution

  • 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