2

I created an online survey tool with Rails (3.2.8). Answers and responses are saved in distinct objects (more than 15 different models in fact) I use devise as a user management system.

After all interviews are finished, admins can modify user responses while they validate the content of each users' interviews. I would like that an attribute called "admin_modified" be set to true whenever an admin validates or modify a response.

I know in MVC I should not get access to the user attributes while in model, but how can I set this attribute to true only when the logged user is an admin without modifying each places where there is a save/create/update_attributes command for 15 different models?

Is there an easy and correct way to do this?

Thanks!

kaligrafy
  • 373
  • 2
  • 6
  • Have you looked into [this](http://stackoverflow.com/questions/2513383/access-current-user-in-model)? – PinnyM Jan 08 '13 at 15:22
  • yes, but as I said, I just want to know if there is a faster way to do this (instead of injecting user object when saving), like an observer that could check ANY save message from ANY object since there are more than 15 different models. – kaligrafy Jan 08 '13 at 15:37
  • You can use the `current_user` method used in the link above together with a standard [observer](http://api.rubyonrails.org/classes/ActiveRecord/Observer.html). – PinnyM Jan 08 '13 at 16:28

1 Answers1

1

Why not store which admin modified / validated the object instead of simply a boolean showing whether it was modified?

Here's how I would implement it:

In User, make a method modify_form_object or even modify_form_object_as_admin which takes the object and the new attributes. You'd call it like this:

@user.modify_form_object(form_object, new_attributes)

And it would set the object's admin_id, and update the object with attributes.


Alternatively you could override the save method of ActiveRecord, check if the current_user is an admin, and assign the field if the field exists.

AJcodez
  • 31,780
  • 20
  • 84
  • 118
  • Yes, that could be even more flexible, but it means I need to find every places where there is a save method. I would have preferred a before_save command, but I know I should not get access to user instance in a model. – kaligrafy Jan 08 '13 at 15:35
  • I'm sure this could help: [ActiveRecord Observer](http://api.rubyonrails.org/classes/ActiveRecord/Observer.html) but I'm not yet familiar with observers. – kaligrafy Jan 08 '13 at 15:40
  • finally, I added an audit method before each save in the controllers – kaligrafy Jan 08 '13 at 20:19