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

标签 mysql ruby-on-rails activerecord

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 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) 问题就会消失 - 但有没有办法处理 tinyint(1) 使用 ActiveRecord 作为数字?

最佳答案

tinyint(1)Hibernate 视为 boolean 时,也会出现同样的问题。诀窍不是使用 tinyint(1),而是使用 tinyint(4)。这样做,RoR 不会假定它是 bool 值。

无论如何,MySQL 中的tinyint(1)tinyint(2) 实际上没有区别。两者可以包含相同的值 - 1 和 2 仅是 column width 的指示符。

See this please

关于mysql - Rails 将 mysql tinyint(1) 视为 bool 值 - 但我希望它是一个数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39971023/

相关文章:

php - 有没有办法在 CodeIgniter 中自动返回所有数据库列?

mysql - 连接两个表并按第一个表主键分组,但也有第二个表行

mysql - 选择连接表中的最小值

PHP 和 MySQL 基于时间的测验应用程序

ruby-on-rails - 如何传递 "link_to"中的隐藏参数

ruby-on-rails - 如何在模型中设置默认值? -- 在 Ruby on Rails 3.1 中

PHP Mysql查询获取特定日期范围内所有星期一的时间范围并将这些不同的开始和结束时间放入数据库中

ruby-on-rails - Ruby:根据指定顺序从散列中连接字段?

ruby-on-rails - Ruby 模型仅显示 key=value 的数据

ruby-on-rails-3 - 导轨 : ActiveRecord Query for has_many :through model