【问题标题】:Best way to add_index to database将索引添加到数据库的最佳方法
【发布时间】:2011-09-08 16:42:38
【问题描述】:

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

我创建价格时:

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

当我将 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

有没有办法从命令行将价格和 user_id 添加到索引?我查看了this question,仍然对如何添加索引感到困惑,而我放置“未添加”的部分似乎很容易出错,因为它们是较早的迁移。

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

感谢您的帮助!

【问题讨论】:

标签: ruby-on-rails


【解决方案1】:

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

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

或者您可以将change 语法与较新版本的rails 一起使用,详情请查看DonamiteIsTnt 评论:

class AddIndexes < ActiveRecord::Migration

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

end

【讨论】:

  • 生成迁移骨架:rails g migration AddIndexes
  • down 方法不应该是 up 的逆方法吗?所以向下应该是“remove_index:prices,:price”,然后是“remove_index:prices,:user_id”。订单很重要,不是吗?
  • 无顺序无关紧要。实际上,使用 Rails 3.1 或更高版本,您只需编写 def change end 即可,无需向上或向下
  • 请注意,在 Mikhail (nudge) 更新此答案之前,the primary way of writing migrations 是通过 change 方法。也就是说,假设您使用的是该链接中列出的“可逆迁移”之一。您只需编写一个 change 方法(而不是 up 方法),rails 会自动推断“down”方法。
  • @DonamiteIsTnt 感谢提醒,已更新答案。
【解决方案2】:

一旦应用程序投入生产,其目的是应用一次迁移

如果您仍在开发您的应用,您可以随时添加它们,然后添加 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

FWIW,add_index :prices 没有意义。索引是按列而不是按表的。

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

CREATE INDEX prices__user_id__idx ON prices (user_id);

【讨论】:

  • 我还能索引一个表吗?
  • 必须在表上为一个或多个列定义索引,明确列出。
【解决方案3】:

简单的解决方案:

  • 创建一个新的迁移
  • 在那里添加索引(它们不需要在旧迁移中)
  • 运行迁移

【讨论】:

    猜你喜欢
    • 2015-01-09
    • 1970-01-01
    • 2015-05-07
    • 2012-02-28
    • 2012-08-15
    • 1970-01-01
    • 2016-10-30
    • 2010-11-13
    • 1970-01-01
    相关资源
    最近更新 更多