Rails 3 watchers and current_user

Stackoverflow has some similar questions about getting the current_user Rails 3 form, but the basic ideas are the same:

1) passing current_user through

attr_accessor :current_user 

in the model that we must observe.

But this is unacceptable to me, since I need to observe 10 models (create, update, delete actions), and I do not want to pass this on for each action for each controller.

2) Saving the current user in Thread. Absolutely unacceptable.

So what is best practice? And let's say I want to get not only current_user in my observer, but also an IP address?

Any ideas?

+4
source share
2 answers

After learning more, I found it completely useless to use Rails native observers in such tasks. Because if you need to transfer something from the controllers, in my case it was current_user, this completely destroys the beauty of the observer.

So my answer to my question is: still stuck with something like acts_as_audited

+1
source

My suggestion is to add the last_modification_by field to the model. In your supervisor, you could use this to find out who made the changes and who gets notified.

Then, so that your view / controller code puts the current user in this field.

It seems to me that this is the safest approach. I will worry about the observer with the help of the current user - it seems to me that the current user should be separated from the quasi-background processing that the observer does. (This is why deterring the current user in Thread - which I have used with great success in the past - is also not the case here).

This approach (having last_modified_by also allows you to make changes to records in batch mode - perhaps by sending an email to the owner of the record, which: "The system updated your record because (there was some daily processing procedure). last_modified_by some was created by the user who represents the system (or admin user).

0
source

Source: https://habr.com/ru/post/1392079/


All Articles