Rails将mysql tinyint(1)视为布尔值-但我希望它是一个数字 [英] Rails sees mysql tinyint(1) as a boolean - but I want it to be a number
问题描述
使用mysql2 gem的Rails 4.2.1.ActiveRecord将数据类型为 tinyint(1)
的mysql列视为布尔值.但是我想使用它作为一个小数字-我想存储最多100个值,对于 tinyint(1)
来说是可以的.当我尝试创建记录时,tinyint列会强制转换为 false
,并且会收到折旧警告:
Rails 4.2.1 using mysql2 gem. ActiveRecord treats a mysql column with data type tinyint(1)
as a boolean. But I want to use it as a small number - I want to store values up to 100 which is ok for tinyint(1)
. When I try to create a record, the tinyint column casts to false
and I get a depreciation warning:
> 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警告:您尝试分配的值不是将
true
或false
显式地显示为布尔列.目前这个值强制转换为false
.这将进行更改以匹配Ruby的语义,并将在Rails 5中强制转换为true
.行为,则应显式处理要转换的值改为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的数字?
If i change the data definition of my_tinyint_col
to tinyint(2)
the problem goes away - but is there a way to treat tinyint(1)
as a number using ActiveRecord?
推荐答案
当 Hibernate将
tinyint(1)
视为 boolean
时,会发生相同的问题.代码>.诀窍不是使用 tinyint(1)
,而是使用 tinyint(4)
.这样做, RoR 不会认为它是布尔值.
Same issue occurs when tinyint(1)
is seen as boolean
by Hibernate
. The trick is not to use tinyint(1)
but to use tinyint(4)
. Doing so, RoR won't assume that it is boolean.
无论如何, MySQL
中的 tinyint(1)
和 tinyint(2)
之间实际上没有区别.两者可以保持相同的值-1和2仅是列宽
的指示符.
At any rate, there is actually no difference between tinyint(1)
and tinyint(2)
in MySQL
. Both can hold the same values - 1 and 2 are signifiers of column width
only.
这篇关于Rails将mysql tinyint(1)视为布尔值-但我希望它是一个数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!