add_index到数据库的最佳方法

Lea*_*RoR 27 ruby-on-rails

我的数据库中已经有以下两个迁移:

当我创造价格时:

class CreatePrices < ActiveRecord::Migration
  def self.up
    create_table :prices do |t|
      t.string :price_name
      t.decimal :price
      t.date :date

      t.timestamps
    end
    # add_index :prices (not added)
  end

  def self.down
    drop_table :prices
  end
end
Run Code Online (Sandbox Code Playgroud)

当我将一个user_id添加到价格时:

class AddUserIdToPrices < ActiveRecord::Migration
  def self.up
    add_column :prices, :user_id, :integer
  end
  # add_index :user_id (not added)
end

  def self.down
    remove_column :prices, :user_id
  end
end
Run Code Online (Sandbox Code Playgroud)

有没有办法从命令行添加价格和user_id到索引?我看了这个问题,仍然对如何添加索引和我放"未添加"的部分感到困惑,因为它们是早期的迁移,因此它们容易出错.

我的问题是,为价格和user_id添加索引的最佳方式是什么?

感谢您的帮助!

Mik*_*kin 57

我认为一个额外的迁移很适合:

class AddIndexes < ActiveRecord::Migration

  def self.up
    add_index :prices, :user_id
    add_index :prices, :price
  end

  def self.down
    remove_index :prices, :user_id
    remove_index :prices, :price
  end

end
Run Code Online (Sandbox Code Playgroud)

或者您可以使用change较新版本的rails语法,查看DonamiteIsTnt注释以获取详细信息:

class AddIndexes < ActiveRecord::Migration

  def change
    add_index :prices, :user_id
    add_index :prices, :price
  end

end
Run Code Online (Sandbox Code Playgroud)

  • 要生成迁移骨架:`rails g migration AddIndexes` (12认同)
  • 请注意,在Mikhail(nudge)更新此答案之前,[编写迁移的主要方式](http://guides.rubyonrails.org/migrations.html#using-the-change-method)是通过更改方法.也就是说,假设您正在使用该链接中列出的"可逆迁移"之一.您只需编写一个更改方法(并且没有向上方法),rails会自动推断出"向下"方法. (3认同)

Eri*_*son 7

应用程序投入生产后,目的是迁移将应用一次.

如果您仍在开发应用程序,则可以随时添加它们,如下所示,rake db:migrate:reset 这将擦除您的数据库并重新创建它.

否则,创建一个新的迁移rails g migration add_user_id_index.

class AddUserIdIndex < ActiveRecord::Migration
  def self.up
    add_index :prices, :user_id
  end

  def self.down
    remove_index :prices, :user_id
  end
end
Run Code Online (Sandbox Code Playgroud)

FWIW,add_index :prices没有意义.索引是每列,而不是每个表.

您始终可以通过登录数据库手动创建索引.

CREATE INDEX prices__user_id__idx ON prices (user_id);
Run Code Online (Sandbox Code Playgroud)