Tutorial :Updating protected attributes using update_all in a migration



Question:

Since you cannot use the normal 'update' and 'update_attribute' methods from ActiveRecord to update a protected attribute, is the following the best way to update an attribute for a single user?

  User.update_all("admin = true","id = 1")  

I'm guessing this doesn't lie in the 'best practice' category, so I'm just curious if there is a more appropriate way.


Solution:1

The best way is to just set it directly, then save the model:

user = User.find(1)  user.admin = true  user.save  

The whole point of protected attributes is so you don't have to constantly worry about filtering them out when doing things like @user.update_attributes(params[:user]) which could otherwise make a non-admin into an admin, or something. Using update_all would prevent validations from running as well, which is almost certainly not what you want.

edit: It looks like this is for a migration, so I would just use update_all or whatever and not worry too much about it. Migrations run once per environment and then never again so don't sweat it too much.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »