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.
The best way is to just set it directly, then save the model:
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. Usingupdate_allwould 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.