0

我有一个这样的模型:

  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 表示短信和电子邮件。这一切在数据库中运行良好,但是当我在脚本/控制台中尝试它时。我意识到这是不可能的(布尔字段上的位掩码)。

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:migrating吗?

4

1 回答 1

1

布尔数据类型表示为 TINYINT(1),因此它是一个字节。如果该字段send_notification用作布尔值,则应该有 '0' - false、'1' - 'true' 或 NULL 值。如果有 valuse > 1,可以用 '1' 更改它们 -

UPDATE settings SET send_notification = 1 WHERE send_notification > 1;

现在,您可以将此字段用于您的标志(NULL、0、1、2...)。如果需要,您可以更改表以将 TINYINT 更改为其他整数类型。

此外,MySQL 具有有用的BIT 功能

于 2011-04-18T07:01:14.397 回答