Adding a column via terminal

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

+6
source share
3 answers

It is better to write a migration, and it is mandatory if you are working with a team. When you make changes to db, you must also update each development environment. Otherwise, you will have crazy developers.

rails generate migration AddPartNumberToProducts part_number:string 

will generate

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

Then migration

 rake db:migrate 

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

Edit:

For the rails command line command line check @tadman's answer or use what Bengala suggested, e.g.

 ActiveRecord::Migration.add_column :products, :part_number, :string 
+8
source

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

For your purpose, the following command will do what you ask:

 > ActiveRecord::Migration.add_column :table_name, :field_name, :field_type 
+8
source

If you just hack, it is usually easier to manipulate the database using the SQLite client, rather than through the Rails DB level.

If you are doing this for a project, create the appropriate migration file and run it.

If you decide to do this, the add_column method is available through the ActiveRecord::Base.connection .

+3
source

Source: https://habr.com/ru/post/920454/


All Articles