开发者

Rails migration: primary key id with unsigned int(10)

开发者 https://www.devze.com 2023-03-19 16:59 出处:网络
I want to define primary key id as below in my 开发者_开发百科tables through rails migration id INT(10) UNSIGNED NOT NULL AUTO_INCREMENT

I want to define primary key id as below in my 开发者_开发百科tables through rails migration

id INT(10) UNSIGNED NOT NULL AUTO_INCREMENT

I am using mysql db.


If you prefer to avoid custom SQL in migrations this will work as well:

create_table(:user, id: false,  primary_key: :id) do |t|
  t.primary_key :id, :unsigned_integer, null: false, default: :null, auto_increment: true
  t.string :name
end


Just use #execute with the SQL you need inside your migration.

execute "ALTER TABLE things MODIFY id UNSIGNED(10) NOT NULL AUTO_INCREMENT"

Or if the column doesn't yet exist at all:

execute "ALTER TABLE things ADD COLUMN id UNSIGNED(10) NOT NULL AUTO_INCREMENT PRIMARY KEY"

That should work fine. I think in your migrations it's fine to drop down to pure SQL, and in many cases it's necessary.


I worked out with this

create_table things, :id => false do |t|
  t.column :id, 'INT UNSIGNED NOT NULL AUTO_INCREMENT, PRIMARY KEY (id)'
  t.string :name
  ...

OR

create_table things, :id => false do |t|
  t.column :id, ID_COLUMN
  t.string :name
  ...

where ID_COLUMN defined in some config/module and used in other migrations as well


Rails 5.2 does accept unsigned

t.integer     :amount,          null: false, unsigned: true
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号