开发者

Updating protected attributes using update_all in a migration

开发者 https://www.devze.com 2023-01-03 06:17 出处:网络
Since you ca开发者_如何学Gonnot 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

Since you ca开发者_如何学Gonnot 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:

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消