10

I'd like to know which fields have been updated after an update_attributes statement. I'm filtering the updatable parameters and deleting those that I don't want updated from the params[:model]. Now, some of the new updatable params might have the same value as the old one and I'd like to know which param was updated and which one was skipped because same value. Here is some of the code:

UPDATABLE_PARAMS = ["param1", "param2", "param3", "param4"]
def update
  @dr = DR.find(params[:id])
  authorize! :update, @dr #devise stuff

  hnew = params[:dr]
  hnew.delete_if {|k, v| !UPDATABLE_PARAMS.include?(k.to_s) }

  if @dr.update_attributes(hnew)
    @dr.update_attribute(:last_updated_by, current_user.email)
    @dr.touch
  end

  render :update_result
end

Here's the tricky part:

I'd like to render the @dr object in JSON (but that's already set) and in addition to its standard fields, I'd like to add a nested object that contains the updated_params. I could just send hnew as @hnew to my view, but if I do that I will get all processed params, not just the ones that were different.

How can I get the changed params?

Andrew Marshall
  • 95,083
  • 20
  • 220
  • 214
Oktav
  • 2,143
  • 2
  • 20
  • 33
  • best practice is to handle allowable mass assigned parameters via attr_accessible and using :as option to assign_attributes/update_attributes/new. – Viktor Trón Jun 18 '12 at 16:28
  • thanks viktor. I'm using attr_accessible but only for new records. The update has different accessible attrs that depend on other factors (like a couple of record field values) – Oktav Jun 19 '12 at 08:49

1 Answers1

39

Map of attributes that were changed when the model was saved.

@dr.previous_changes() 
Yuri Barbashov
  • 5,407
  • 1
  • 24
  • 20