Ruby on Rails Rails Cookbook - Advanced rails recipes/learnings and coding techniques Playing with Tables using rails console


Example


View tables

ActiveRecord::Base.connection.tables

Delete any table.

    ActiveRecord::Base.connection.drop_table("users")
    ------------OR----------------------
    ActiveRecord::Migration.drop_table(:users)
    ------------OR---------------------
    ActiveRecord::Base.connection.execute("drop table users")

Remove index from existing column

 ActiveRecord::Migration.remove_index(:users, :name => 'index_users_on_country')

where country is a column name in the migration file with already added index in users table as shown below:-

 t.string :country,add_index: true

Remove foreign key constraint

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

where menus has_many food_items and their respective migrations too.

Add column

ActiveRecord::Migration.remove_column :table_name, :column_name

for example:-

 ActiveRecord::Migration.add_column :profiles, :profile_likes, :integer, :default => 0