我有一个这样的模型:
create_table :settings do |t|
t.integer :user_id
t.boolean :send_notification, :default => true
end
它运行良好,直到我需要指定多种类型的通知(电子邮件和/或短信)并且我希望用户能够指定他需要哪种通知。所以当我查看数据库中的设置表时,我认为这是可行的:
+----------------------+------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------------------+------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| user_id | int(11) | YES | MUL | NULL | |
| send_notification | tinyint(1) | YES | | 1 | |
+----------------------+------------+------+-----+---------+----------------+
所以我想重用带有位屏蔽的 send_notification 列,例如0 表示无任何内容,1 表示仅发送电子邮件,2 表示仅发送短信,3 表示同时发送短信和电子邮件。它在数据库中运行良好,但是当我在脚本/控制台中尝试它时。我意识到这是不可能的( boolean 字段上的位屏蔽)。
ree > setting = Setting.first
=> #<Setting id: 1, user_id: 1, send_notification: false>
ree > setting.send_notification = 2
=> 2
ree > setting
=> #<Setting id: 1, user_id: 1, send_notification: false>
所以我需要更改列类型,但是由于我的表很大,所以成本有点高。除了创建迁移文件和rake db:migration
之外,还有更好的解决方案吗?
最佳答案
boolean 数据类型表示为 TINYINT(1),因此它是一个字节。如果 send_notification
字段用作 boolean 值,则应该有“0”- false、“1”-“true”或 NULL 值。如果有值 > 1,则可以用 '1' 更改它们 -
UPDATE settings SET send_notification = 1 WHERE send_notification > 1;
现在,您可以将此字段用作您的标志(NULL、0、1、2...)。如果需要,您可以更改表以将 TINYINT 更改为其他整数类型。
此外,MySQL 还有有用的 BIT functions .
关于mysql - 如何在没有数据库的情况下将事件记录列类型从 boolean 值更改为整数:migrate?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5699317/