我的数据库中已经进行了以下两次迁移:
当我创建价格时:
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添加索引的最佳方式是什么?
感谢您的帮助!
答案 0 :(得分: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
或者您可以在较新版本的rails中使用change
语法,请查看DonamiteIsTnt
条评论以获取详细信息:
class AddIndexes < ActiveRecord::Migration
def change
add_index :prices, :user_id
add_index :prices, :price
end
end
答案 1 :(得分: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
FWIW,add_index :prices
没有意义。索引是每列,而不是每个表。
您始终可以通过登录数据库手动创建索引。
CREATE INDEX prices__user_id__idx ON prices (user_id);
答案 2 :(得分:4)
简单的解决方案: