我的数据库中已经有以下两个迁移:
当我创造价格时:
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)
应用程序投入生产后,目的是迁移将应用一次.
如果您仍在开发应用程序,则可以随时添加它们,如下所示,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)
归档时间: |
|
查看次数: |
30969 次 |
最近记录: |