Rails 4.2.1 使用 mysql2 gem。 ActiveRecord 将数据类型为 tinyint(1)
的 mysql 列视为 bool 值。但我想将它用作一个小数字 - 我想存储最多 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
orfalse
to a boolean column. Currently this value casts tofalse
. This will change to match Ruby's semantics, and will cast totrue
in Rails 5. If you would like to maintain the current behavior, you should explicitly handle the values you would like cast tofalse
.
如果我将 my_tinyint_col
的数据定义更改为 tinyint(2)
问题就会消失 - 但有没有办法处理 tinyint(1)
使用 ActiveRecord 作为数字?
最佳答案
当 tinyint(1)
被 Hibernate
视为 boolean
时,也会出现同样的问题。诀窍不是使用 tinyint(1)
,而是使用 tinyint(4)
。这样做,RoR 不会假定它是 bool 值。
无论如何,MySQL
中的tinyint(1)
和tinyint(2)
实际上没有区别。两者可以包含相同的值 - 1 和 2 仅是 column width
的指示符。
关于mysql - Rails 将 mysql tinyint(1) 视为 bool 值 - 但我希望它是一个数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39971023/