如何在Ruby on Rails中创建tinyint(2)或tinyint(3)类型的列?

max*_*son 12 mysql ruby-on-rails tinyint rails-migrations

在Ruby on Rails中,迁移中的以下代码tinyint(4)在MySQL中创建了一个类型列:

create_table :great_table do |t|
    t.integer :step_position, :limit => 1 #tinyint
end
Run Code Online (Sandbox Code Playgroud)

我将如何创建类型的列tinyint(2)tinyint(3)

小智 18

对于tinyint(2)

create_table :great_table do |t|
  t.integer :step_position, :limit => 2
end
Run Code Online (Sandbox Code Playgroud)

对于tinyint(3)

create_table :great_table do |t|
  t.integer :step_position, :limit => 3
end
Run Code Online (Sandbox Code Playgroud)


小智 8

根据我在 gem 的源代码中看到的内容,您不能:

     # File activerecord/lib/active_record/connection_adapters/mysql_adapter.rb, line   540  
     540:       def type_to_sql(type, limit = nil, precision = nil, scale = nil)
     541:         return super unless type.to_s == 'integer'
     542: 
     543:         case limit
     544:         when 1; 'tinyint'
     545:         when 2; 'smallint'
     546:         when 3; 'mediumint'
     547:         when nil, 4, 11; 'int(11)'  # compatibility with MySQL default
     548:         when 5..8; 'bigint'
     549:         else raise(ActiveRecordError, "No integer type has byte size #{limit}")
     550:         end
     551:       end
Run Code Online (Sandbox Code Playgroud)

type_to_sql


pet*_*.np 5

tinyint(4)MySQL 中根本不存在这样的东西。tinyint是一个单字节有符号整数。您可以在文档中检查所有整数类型。tinyint(1)您可能会在 Rails源代码中看到类似的内容,但我认为这是一个同义反复,因为tinyint已经暗示了一个字节存储。

RailsTINYINT, SMALLINT, MEDIUMINT, INT, BIGINT在迁移中声明的方法是使用适当的字节大小,如源代码limit:中所示。

请注意,Rails 默认情况下会将一字节整数视为布尔值,从上面的链接可以看出。

  • 实际上,括号之间的数字与用于存储的字节数无关。它只是指定显示宽度,显示该数字的应用程序可能会也可能不会选择遵守。https://dev.mysql.com/doc/refman/8.0/en/numeric-type-attributes.html (2认同)