Rails:确保一次只将一个布尔字段设置为 true [英] Rails: Ensure only one boolean field is set to true at a time
问题描述
我有一个 Logo 模型,它有 name:string 和 default:boolean 字段.我希望 true 值是唯一的,以便一次只能将数据库中的一项设置为 true.如何在控制器中设置更新和新操作,以将徽标的所有其余值设置为 false?
I have a Logo model that has fields of name:string, default:boolean. I want the true value to be unique so that only one item in the database can be set to true at once. How do I set my update and new actions in my controller to set all the rest of the values of my logos to false?
假设我有以下设置在我的数据库中
模型标志
名称:字符串 |默认值:布尔值 |
项目 1 |真的|
项目2 |假|
第 3 项 |假|
Let's say I have the following setup
in my database
Model Logo
name:string | default:boolean |
Item1 | true |
Item2 | false |
Item3 | false |
如果我将 Item2 默认值更改为 true,我希望它遍历所有徽标并将其余徽标设置为 false,因此一次只有一个为 true,因此看起来像这样.
If I change Item2 default value to true, I want it to loop through all logos and set the rest of them to false, so only one is true at once, so it looks like this.
名称:字符串 |默认值:布尔值 |
项目 1 |假|
项目2 |真的|
第 3 项 |假|
name:string | default:boolean |
Item1 | false |
Item2 | true |
Item3 | false |
提前感谢您的帮助.
推荐答案
这段代码是从以前的答案中偷来的,稍微简化了:
This code is stolen from previous answer and slightly simplified:
def falsify_all_others
Item.where('id != ?', self.id).update_all("default = 'false'")
end
您可以在模型的 before_save 回调中使用此方法.
You can use this method in before_save callback in your model.
实际上,最好只伪造"那些值为真"的记录,就像这样:
Actually, it is better to "falsify" only records which values are 'true', like this:
Item.where('id != ? and default', self.id).update_all("default = 'false'")
更新:为了保持代码干燥,使用 self.class
而不是 Item
:
UPDATE: to keep code DRY, use self.class
instead of Item
:
self.class.where('id != ? and default', self.id).update_all("default = 'false'")
这篇关于Rails:确保一次只将一个布尔字段设置为 true的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!