Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding which fields have been updated after calling update_attributes?

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?

like image 601
Oktav Avatar asked Jun 18 '12 11:06

Oktav


People also ask

Does Update_attributes call save?

update_attribute calls save on the object, which is unnecessary in this case, since the statement is inside a before_save callback and will get saved anyway.

How do you update attributes in Ruby on Rails?

Use update_attribute to change an attribute and persist it without running validations. Use update to change an attribute, check the validations and persist the change if validations pass. You can find an object and update it with a one command using update as class method.


1 Answers

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

@dr.previous_changes() 
like image 103
Yuri Barbashov Avatar answered Oct 22 '22 11:10

Yuri Barbashov