Ruby on Rails:更新数据库中的布尔记录

11

如果我的数据库设置为false,那么在更新布尔值时最佳实践是什么?

我可以在控制台上执行操作:

>> u = User.find_by_id(1)

我接下来该做什么?

谢谢

2个回答

17

如果您想切换布尔值:

u.toggle!(:<attribute>)  # Toggles the boolean and saves without validations
u.toggle(:<attribute>)   # Toggles the boolean and does not save

如果您想设置布尔值:

u.<attribute> = [true|false]

如果您想立即更新布尔值:

u.update_column(:<attribute>, [true|false])  # Doesn't update timestamps or call callbacks
u.update_attribute(:<attribute>, [true|false])  # Updates timestamps and triggers any callbacks

这种用法会导致错误,你应该使用u.toggle!(<attribute>)。 - Serhan
1
谢谢,@Serhan。已修复。 - pdobb

0

我正在Heroku上尝试这个,我在heroku run console中,它说undefined method 'boolean_property。另外,我正在尝试将其更新为true - hellomello

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接