Question

I am working through One Month Rails and I am confused about the following line of code

rails generate migration add_user_id_to_pins user_id:integer:index

The code generates this file in the migrate folder within db:

class AddUserIdToPins < ActiveRecord::Migration
  def change
    add_column :pins, :user_id, :integer
    add_column :pins, :index
  end
end

I accidentally typed

rails generate migration add_user_id_to_pins user_id:integer index:integer

just because I assumed the syntax was "variable name":"type of variable name"

and my command generated the following migration file:

class AddUserIdToPins < ActiveRecord::Migration
  def change
    add_column :pins, :user_id, :integer
    add_column :pins, :index, :integer
  end
end

Can someone please explain the syntax, and also why there is the symbol integer on both lines in my code, vs. only the first line of the first command's generated code, and also explain the implications of continuing to use my code vs. the example.

Was it helpful?

Solution

rails generate migration add_user_id_to_pins user_id:integer:index

This Indicates that you have PIN model and you want to add extra attribute named user_id to pins.

I think you have relation between pin and user. like either

user has_many pins
pin belongs_to user

or

user has_one pin
pin belongs_to user

right command to run migration is

rails g migration add_user_id_to_pins user_id:integer

user_id : field name
Integer : Type that you assigned to user_id.

Stores only id of the user.

def change
  add_column :pins, :user_id, :integer
end

This is what you can see in migration file.

You have added index wrong way. like you can add index manually. after generation migration file go to that migration and add

  add_index :pins, :user_id

For ActiveRecord Migration : http://guides.rubyonrails.org/migrations.html For Index In rails refer this : https://tomafro.net/2009/08/using-indexes-in-rails-index-your-associations

Hope you can understand what is migration and what/why index.

OTHER TIPS

Check your migration file again. The second line should have been add_index instead of add_coumn.

From the doc:

If you'd like to add an index on the new column, you can do that as well:

$ rails generate migration AddPartNumberToProducts part_number:string:index

will generate

class AddPartNumberToProducts < ActiveRecord::Migration
  def change
    add_column :products, :part_number, :string
    add_index :products, :part_number
  end
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top