【问题标题】:Rails change_column removing index from schemaRails change_column 从模式中删除索引
【发布时间】:2016-02-02 05:20:42
【问题描述】:

我正在尝试使某些列不能为空。我使用change_column 没问题,但其中一些列附有一个索引,表示它是唯一的。

但是,当我运行此迁移时:

change_column :users, :username, :string, null: false
change_column :users, :email, :string, null: false
change_column :users, :password, :string, null: false
change_column :users, :terms_agreed, :boolean, null: false

它会删除架构中的add_index

schema.rb

- add_index "users", ["username"], :name => "index_users_on_username_code", :unique => true
- add_index "users", ["email"], :name => "index_users_on_email_code", :unique => true
add_index "users", ["confirmation_code"], :name => "index_users_on_confirmation_code", :unique => true

如何在不删除索引的情况下执行此操作?

附:它实际上并没有删除数据库中的索引。就在schema.rb 文件中。

【问题讨论】:

    标签: mysql ruby-on-rails ruby-on-rails-3.2 rails-migrations


    【解决方案1】:

    如何处理迁移的行为取决于您的数据库实现。更多信息here,但在您的迁移中,您应该在您的change 中明确请求索引。

    class DoSomethingToTable < ActiveRecord::Migration
      def change
        change_column :users, :username, :string, null: false, index: true
      end
    end
    

    有关更多信息,请参阅文档information

    【讨论】:

      【解决方案2】:

      所以仍然不清楚发生了什么,但事实证明在某些数据库操作期间索引已从数据库中删除。

      我只是将架构放回我需要的方式并运行rake db:setup,然后我再次迁移,一切正常。非常令人困惑,并且花费了大量不必要的时间试图弄清楚。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-12-07
        • 2022-07-20
        • 2019-09-30
        • 1970-01-01
        • 1970-01-01
        • 2019-07-09
        • 2020-12-06
        相关资源
        最近更新 更多