Playing with tables in the Rails console

suggest change

View tables

ActiveRecord::Base.connection.tables

Drop a table. This deletes the table and its rows.

ActiveRecord::Base.connection.drop_table(:users)

Prefer a migration for anything you need to run again. ActiveRecord::Migration.drop_table is not a stable console call.

Remove an index

ActiveRecord::Base.connection.remove_index(:users, name: "index_users_on_country")

That name matches an index on country. Inside create_table, declare the column and the index like this. add_index: true is not a column option.

t.string :country, index: true

Remove a foreign key

ActiveRecord::Base.connection.remove_foreign_key(:food_items, :menus)

Use this when menus has many food_items and the foreign key was added in a migration.

Add a column

ActiveRecord::Base.connection.add_column(:profiles, :profile_likes, :integer, default: 0)

Remove a column

ActiveRecord::Base.connection.remove_column(:profiles, :profile_likes)

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents