Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a column through the terminal

How do you add a column to a table using ActiveRecord through the terminal. I am trying to use add_column method but its not working. Any ideas please?

like image 956
Sweebo Avatar asked Jul 13 '12 20:07

Sweebo


People also ask

How do I add a column in SQL terminal?

Syntax. The syntax to add a column in a table in MySQL (using the ALTER TABLE statement) is: ALTER TABLE table_name ADD new_column_name column_definition [ FIRST | AFTER column_name ]; table_name.

Which command is used to add the column for department?

The command add column is used to add an additional column to any given MySQL table. To do this, you must specify the column name and type. Note: The add column command is sometimes referred to as additional column or new column.


2 Answers

It is better to write a migration and a must if you are working with a team. When you make db changes, then every developer's environment has to be updated also. Otherwise, you will have some mad developers at you.

rails generate migration AddPartNumberToProducts part_number:string

will generate

class AddPartNumberToProducts < ActiveRecord::Migration
  def change
    add_column :products, :part_number, :string
  end
end

Then you run the migration

rake db:migrate

http://guides.rubyonrails.org/migrations.html

Edit:

For a rails console command line check @tadman's answer or use what Bengala proposed like

ActiveRecord::Migration.add_column :products, :part_number, :string
like image 129
Sully Avatar answered Sep 22 '22 22:09

Sully


You can run migrations directly in rails console rails c with ActiveRecord::Migration

For your purpose the next command will do what you ask:

>   ActiveRecord::Migration.add_column :table_name, :field_name, :field_type
like image 41
Bengala Avatar answered Sep 21 '22 22:09

Bengala