Rails 迁移:如何通过使用 ROR 迁移来增加列数据类型大小

问题描述 投票:0回答:3

我的用户表登录列是字符串类型,限制为 40 个字符。 现在我计划将限制增加到 55 个字符。

任何人请告诉我如何通过使用 ROR 迁移来增加此限制。

谢谢, 斯拉文

ruby-on-rails ruby migration
3个回答
78
投票
class YourMigration < ActiveRecord::Migration
  def up
    change_column :users, :login, :string, :limit => 55
  end

  def down
    change_column :users, :login, :string, :limit => 40
  end
end

29
投票
class YourMigration < ActiveRecord::Migration
  def change
    change_column :users, :login, :string, :limit => 55
  end
end

0
投票

增加字符限制后,假设您插入一些长度超过 40 个字符的数据。

现在运行

db:rollback
,一些现有数据无法容纳 40 个字符:

  • 可能会显示数据库错误,或者,
  • 在现有数据中,字符串将被截断,并且您将丢失一些字符。

为了避免此问题,我增加了

up
中的限制,但是,请勿更改
down
中的任何内容。

class FixUsersLogin < ActiveRecord::Migration
  def up
    change_column :users, :login, :string, limit: 55
  end

  def down
    # do nothing in rollback
  end
end
© www.soinside.com 2019 - 2024. All rights reserved.