【问题标题】:how to change the index of the table that was already created using rails migration?如何更改已使用 Rails 迁移创建的表的索引?
【发布时间】:2015-07-15 00:47:38
【问题描述】:

我已经创建了这个迁移文件并运行了迁移。

class CreateStudentContexts < ActiveRecord::Migration
  def change
    create_table :student_contexts do |t|
      t.string :student_id, index: true, null: false, limit: 40
      t.text :data
      t.timestamps null: false

      t.index [:student_id, :updated_at], unique: true, name: 'student_context_index'
    end
  end
end

现在我想创建一个新的迁移文件来更新索引,索引字段应该是 student_id 和 created_at。

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-4 rails-activerecord rails-migrations


    【解决方案1】:

    这个问题有点老了,但万一有人遇到它:

    贾斯汀伍德的回答应该可以,但有一个变化:将 remove_index 方法中的列名替换为索引的名称:

    remove_index :student_contexts, name: 'student_context_index'
    

    创建索引时,它使用name 参数指定了一个特定(非标准)名称,因此您还需要在remove_index 语句中使用name 参数。否则,Rails 期望索引具有标准名称(在本例中为“index_student_contexts_on_updated_at”)。

    【讨论】:

      【解决方案2】:

      您可以创建另一个迁移并更改表。类似的东西

      class MyMigration < ActiveRecord::Migration
        def change
          remove_index :student_contexts, :updated_at
          add_index :student_contexts, :created_at
        end
      end
      

      会的。

      【讨论】:

      • 它抛出一个错误,“`index_name_for_remove': 发生错误,这个和所有后来的迁移被取消:(StandardError)” 表'student_contexts'上的索引名称'index_student_contexts_on_updated_at'不存在跨度>
      猜你喜欢
      • 2018-01-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-21
      • 2011-05-11
      • 1970-01-01
      • 2015-03-01
      相关资源
      最近更新 更多