我想生成一个迁移,将列添加到数据类型为unsigned int的表中。我希望用它来存储this article中提到的IP地址。
我遇到了this question但它会使迁移数据库依赖,不知道如何以更好的方式做到这一点吗?
答案 0 :(得分:15)
此处显示了一个可行的解决方案,可让您在rails迁移中更原生地执行此操作:unsigned int field in a Ruby on Rails migration?
为了长寿,答案是在无类型列的选项中添加自定义规范:
t.column :population, 'integer unsigned'
我认为使用'integer unsigned'是合理的数据库无关,但可能不是100%。如果您愿意将自己锁定在特定的数据库中,也可以使用“BIGINT unsigned”之类的东西。
另外,我对Geoff的回答感到有些失望,因为它似乎完全无视使用相同数量的存储空间时无符号整数保存不同数据集这一事实。如果您知道自己不需要负数且有兴趣优化数据存储需求,那么无符号整数就很有价值。要查看mysql的指南,请参阅: http://dev.mysql.com/doc/refman/5.5/en/integer-types.html
请注意下面的JellicleCat注释,架构文件不会跟踪此更改,因此在加载架构时,列的签名方面将会丢失。
答案 1 :(得分:8)
第1步:
将activerecord-mysql-unsigned添加到GemFile
# add unsigned integer support to mysql2 adapter
gem "activerecord-mysql-unsigned", "~> 0.0.1"
第2步: 安装宝石
bundle install
第3步:
在您喜欢的字段中使用“unsigned:true”
t.integer :cost, unsigned: true
参考:http://rubydoc.info/gems/activerecord-mysql-unsigned/0.0.1/frames
答案 2 :(得分:1)
您可以通过执行SQL查询
来完成 在MySQL查询的情况下将
添加新列
ALTER TABLE table_name ADD column_name INT unsigned;
要删除列
ALTER TABLE table_name DROP column_name;
迁移:
class MyMigration < ActiveRecord::Migration
def self.up
execute "ALTER TABLE table_name ADD column_name INT unsigned;"
end
def self.down
execute "ALTER TABLE table_name DROP column_name;"
end
end
答案 3 :(得分:-7)
对不起。 Unsigned不是受支持的Rails数据类型之一。
请参阅以下指南的第1.4节。
http://guides.rubyonrails.org/migrations.html
我不确定你为什么认为你需要签名。整数和无符号都采用相同的位数,被签名只是表示您希望将其中一个位解释为有符号位的约定。如果你指定了一个打开签名位的值,数据库会认为它是一个负数,但是你会更清楚,你可以对自己微笑,因为你意识到你仍然比机器更聪明。
我希望有所帮助。