Ruby on rails 向数据库添加索引的最佳方法
我的数据库中已经有以下两个迁移: 当我创建价格时:Ruby on rails 向数据库添加索引的最佳方法,ruby-on-rails,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 adde
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
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
class CreatePrices
当我在价格中添加用户id时:
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
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
class AddUserIdToPrices
从命令行是否有方法将价格和用户id添加到索引?我看了一下,仍然对如何添加索引感到困惑,我放在“notadded”中的部分似乎很容易出错,因为它们是较早的迁移
我的问题是,对我来说,向价格和用户id添加索引的最佳方式是什么
谢谢你的帮助 我认为一个额外的迁移非常合适:
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
简单解决方案:
- 创建新的迁移
- 在那里添加索引(它们不需要在较旧的迁移中)
- 运行迁移
rake db:migrate:reset
,这将擦除您的数据库并重新创建它
否则,创建一个新的迁移rails g migration add\u user\u id\u index
class AddUserIdIndex < ActiveRecord::Migration
def self.up
add_index :prices, :user_id
end
def self.down
remove_index :prices, :user_id
end
end
要生成迁移框架:
rails g migration AddIndexes
down方法不应该是up方法的倒数吗?所以应该是“remove_index:prices,:price”,然后是“remove_index:prices,:user_id”。秩序很重要,不是吗?没有秩序不重要。实际上,在Rails 3.1或更高版本中,您只需编写def change end
,而无需向上或向下。请注意,在Mikhail(轻推)更新此答案之前,是通过更改方法完成的。也就是说,假设您正在使用该链接中列出的“可逆迁移”之一。您只需编写一个change方法(而不是up方法),rails就会自动推断出“down”方法。@谢谢提醒,回答已更新。我仍然可以为表编制索引吗?必须为表中的一个或多个列定义索引,并显式列出。请看这个问题-