Friday, August 12, 2016

How to remove a column from a table in Rails console?

>> ActiveRecord::Migration.remove_column(:products, :price)
-- remove_column(:products, :price)
   (0.1ms)  begin transaction
   (0.7ms)  CREATE TEMPORARY TABLE "aproducts" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "name" varchar, "price" decimal, "created_at" datetime NOT NULL, "updated_at" datetime NOT NULL)
   (0.4ms)  INSERT INTO "aproducts" ("id","name","price","created_at","updated_at")
                     SELECT "id","name","price","created_at","updated_at" FROM "products"
   (0.3ms)  DROP TABLE "products"
   (0.2ms)  CREATE TABLE "products" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "name" varchar, "created_at" datetime NOT NULL, "updated_at" datetime NOT NULL)
   (0.1ms)  INSERT INTO "products" ("id","name","created_at","updated_at")
                     SELECT "id","name","created_at","updated_at" FROM "aproducts"
   (0.2ms)  DROP TABLE "aproducts"
   (49.8ms)  commit transaction
   -> 0.0624s
=> []
 

You have to exit the Rails console and go into Rails console again:

rails c
Loading development environment (Rails 5.0.0)
>> Product.columns.map{ |c| [c.name, c.type]}
=> [["id", :integer], ["name", :string], ["created_at", :datetime], ["updated_at", :datetime]]

You can now see that the price column has been removed from the products table.


No comments:

Post a Comment