views:

73

answers:

1

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.

+2  A: 

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.

x1a4
That is what I originally tried but that doesn't seem to work in my migration, while update_all does work...
Jack
Oh, this is a migration? You should have said so :pYeah, just use update_all and don't worry about it.
x1a4
I didn't think it would make a difference... My bad. Why doesn't it work in migrations??
Jack
It should work in migrations as it would anywhere else. I'm wondering what else might be at work in that case, but for a migration I just don't think it's worth worrying too much over.
x1a4
True. Just sorta lost my mind over it trying to figure out what was at play
Jack