`
fantaxy025025
  • 浏览: 1247562 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类

Rails_migrations中使用mysql的bigint

 
阅读更多

From:http://rubyer.me/blog/468/

 

使用mysql时,integer最大是2147483647(10位)。如果想存储更大的数字就要使用BIGINT。比如现在QQ号已经有11位,很快就12位了。

搜索好久一直没找到好的办法,有人说要装插件,但我看了一下插件很久没更新了。后来看了下mysql_adapter源码找到答案,源码片段如下:

 

# activerecord-3.0.9/lib/active_record/connection_adapters/mysql_adapter.rb
# Maps logical Rails types to MySQL-specific data types.
def type_to_sql(type, limit = nil, precision = nil, scale = nil)
  return super unless type.to_s == 'integer'

  case limit
  when 1; 'tinyint'
  when 2; 'smallint'
  when 3; 'mediumint'
  when nil, 4, 11; 'int(11)'  # compatibility with MySQL default
  when 5..8; 'bigint'
  else raise(ActiveRecordError, "No integer type has byte size #{limit}")
  end
end

 所以我们可以添加:limit => 5/6/7/8来得到一个bigint列。

t.integer :qq, :limit => 8

 如果想设置id为bigint,还要在create_table时传递:id => false,然后手动指定id列。

class CreateDemo < ActiveRecord::Migration
  def self.up
    create_table :demo, :id => false do |t|
      t.integer :id, :limit => 8
    end
  end
end

 

 

===

==

=

I

=

==

===

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics