Sweebo
Sweebo

Reputation: 336

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?

Upvotes: 20

Views: 21165

Answers (3)

Sully
Sully

Reputation: 14943

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

Upvotes: 32

Miguel Peniche
Miguel Peniche

Reputation: 1032

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

Upvotes: 29

tadman
tadman

Reputation: 211560

If you're just hacking around, it's usually easier to manipulate the database using a SQLite client of some sorts than through the Rails DB layer.

If you're doing this for a project, create a proper migration file and run it.

If you're determined to do this, the add_column method is available through the ActiveRecord::Base.connection driver object.

Upvotes: 3

Related Questions