Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to add_index to database

I have the following two migrations already in my database:

When I created Prices:

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 

and when I added a user_id to Prices:

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 

Is there a way from the command line to add prices and user_id to index? I looked at this question and still was confused on how to go about adding indexes and the parts where I put "not added" seem like they would be error-prone because they were earlier migrations.

My question is, what is the best way for me to add indexing to prices and user_id?

Thank you for the help!

like image 597
LearningRoR Avatar asked Jun 05 '11 10:06

LearningRoR


People also ask

What does add_ index do?

It adds a multi-column index on columns one and two in resources table.

What is the use of add_index in rails?

This allows for faster lookup by only grabbing all of the names in the name column in our database, then comparing it to our search query of the name we are looking for. Adding an index can also be used in the case of a join table.

How do I create a Rails migration?

Generate migrations The way of creating migration by using the rails generates command in rails command prompt. First open rails command prompt in start>>Railsinstaller>>command prompt then root your application directory.

How do I rollback migration in Rails?

You must rollback the migration (for example with bin/rails db:rollback ), edit your migration, and then run bin/rails db:migrate to run the corrected version.


1 Answers

I think one extra migration fits well:

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 

Or you can use change syntax with newer versions of rails, look at DonamiteIsTnt comment for details:

class AddIndexes < ActiveRecord::Migration    def change     add_index :prices, :user_id     add_index :prices, :price   end  end 
like image 127
Mikhail Nikalyukin Avatar answered Oct 14 '22 10:10

Mikhail Nikalyukin