数据库
首页 > 数据库> > Rails将mysql tinyint(1)视为布尔值-但我希望它是一个数字

Rails将mysql tinyint(1)视为布尔值-但我希望它是一个数字

作者:互联网

Rails 4.2.1使用mysql2 gem. ActiveRecord将数据类型为tinyint(1)的mysql列视为布尔值.但是我想使用它作为一个小数字-我想存储最多100个值,这对于tinyint(1)来说是可以的.当我尝试创建记录时,tinyint列会转换为false,并且会出现折旧警告:

> Foo.create(my_tinyint_col: 13)
  (0.2ms)  BEGIN
    SQL (0.5ms)  INSERT INTO `foos` (`my_tinyint_col`) VALUES (0)
  (107.3ms)  COMMIT
  => #<Foo ID: 519, my_tinyint_col: false> 

DEPRECATION WARNING: You attempted to assign a value which is not
explicitly true or false to a boolean column. Currently this value
casts to false. This will change to match Ruby’s semantics, and will
cast to true in Rails 5. If you would like to maintain the current
behavior, you should explicitly handle the values you would like cast
to false.

如果我将my_tinyint_col的数据定义更改为tinyint(2),问题就消失了-但是有没有办法使用ActiveRecord将tinyint(1)视为数字?

解决方法:

当Hibernate将tinyint(1)视为布尔值时,也会发生相同的问题.诀窍不是使用tinyint(1),而是使用tinyint(4).这样做,RoR不会认为它是布尔值.

无论如何,MySQL中的tinyint(1)和tinyint(2)之间实际上没有区别.两者可以保持相同的值-1和2仅是列宽的指示符.

See this please

标签:activerecord,ruby-on-rails,mysql
来源: https://codeday.me/bug/20191118/2025410.html