I would like to show the users which fields have been modified following his PUT/PATCH request
For example, I have a big "project" form, with several fields, but my user decided to only update the deadline and the project name. After he clicks the "save" button, I would like to show some message saying "You have successfully updated : name, deadline"
If it's possible, I would like some generic code that would detect the update action and infer the variable name. By generic I mean, I want to implement this in my ApplicationController, so I don't have to add code in every controller#update action
Let's look at this sample code from controllers/entreprise_controller.rb
def update
if @entreprise.update_attributes(entreprise_params)
redirect_to @entreprise, notice: "Entreprise éditée"
else
render 'edit'
end
end
Here's an idea of steps to reach my goal. Could you help me with each of these ? Or suggest a better approach ?
- Detect that we are doing a CRUD
update
action, for example from the action name in the code, that should always beupdate
(how can I read, from the code, the name of the action being executed ?) - Guess the variable name : here
@entreprise
, it can be inferred from the file for example (or maybe callingself.class
and doing some regex ?) - Save the list of variables that are going to be updated (maybe some tricks involving
before_action
andafter_action
and dirty_tracking ? See my edit.) - Provide this list as a GET argument for the
redirect to @entreprise
(should be pretty straightforward) - Show this list to the user (this part is OK for me)
EDIT concerning Dirty Tracking
Mongoid already implements this. However the main problem is getting the intermediate variable before it is saved. Each controller instanciates the variable like @entreprise
during a before_action
callback. And if I add a before_action
in my ApplicationController, it will fire before, so no variable is available yet. And as regards a possible after_action
in ApplicationController, the doc says "Any persistence operation clears the changes." so it's dead already. I probably cannot get away without rewriting every controller ?
Dirty Tracking & controller in a nutshell :
prepend_before_action
before_action
of ApplicationControllerbefore_action
of EntrepriseController (which includes set_entreprise, where the variable@entreprise
is defined so as to proceed with update)- If we can get a callback to HERE, it would let us inspect the object for dirty tracking information, as the object exist in memory, we can use
@entreprise.attributes=entreprise_params
and look at the dirty info (where entreprise_params is the strong parameters for @entreprise) - action : on success, it will store the info in the DB, and we lose dirty tracking info
after_action