0

Since I am new to Rails, I am following this 'getting started' guide on rails website.

On section 6.1 Generating a Model, I should run rails generate model Comment commenter:string body:text post:references to get a comment model.

Supposedly, this is what should be included in the migration file:

class CreateComments < ActiveRecord::Migration
   def change
     create_table :comments do |t|
       t.string :commenter
       t.text :body
       t.references :post

       t.timestamps
     end

     add_index :comments, :post_id
   end
end

But in my migration file, I have everything but this line add_index :comments, :post_id. Instead, I have index:true following the t.references :post

I can't seem to find an explanation to this, can anyone explain to me what is going on here? Because later on I need to use :post_id, but in my version of migration, it is not clearly declared. I am very confused.

1
  • post your exact migration file Commented Dec 26, 2013 at 12:35

2 Answers 2

2
class CreateComments < ActiveRecord::Migration
  def change
     create_table :comments do |t|
       t.string :commenter
       t.text :body
       t.references :post

       t.timestamps
     end

     add_index :comments, :post_id
  end
end  

and

class CreateComments < ActiveRecord::Migration
  def change
     create_table :comments do |t|
       t.string :commenter
       t.text :body
       t.references :post, index: true

       t.timestamps
     end

  end
end

will do same things, both of them will add index to post_id column

also you can later add index to any column any column that you want to add to your model like

$ rails generate migration AddPartNumberToProducts part_number:string:index

that will produce this code:

class AddPartNumberToProducts < ActiveRecord::Migration
  def change
    add_column :products, :part_number, :string
    add_index :products, :part_number
  end
end
Sign up to request clarification or add additional context in comments.

1 Comment

Good to know, but is that a new feature of using "index:true"?
0

in above code if you want to create index for post_id then write it as t.integer :post_id else you can try this add_index :comments, :post

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.