Check if a table exists in Rails - ruby-on-rails

I have a rake task that won't work unless a table exists. I'm working with more than 20 engineers on a website so I want to make sure they have migrated the table before they can do a rake task which will populate that respective table.
Does AR have a method such as Table.exists? How can I make sure they have migrated the table successfully?

In Rails 5 the API became explicit regarding tables/views, collectively data sources.
# Tables and views
ActiveRecord::Base.connection.data_sources
ActiveRecord::Base.connection.data_source_exists? 'kittens'
# Tables
ActiveRecord::Base.connection.tables
ActiveRecord::Base.connection.table_exists? 'kittens'
# Views
ActiveRecord::Base.connection.views
ActiveRecord::Base.connection.view_exists? 'kittens'
In Rails 2, 3 & 4 the API is about tables.
# Listing of all tables and views
ActiveRecord::Base.connection.tables
# Checks for existence of kittens table/view (Kitten model)
ActiveRecord::Base.connection.table_exists? 'kittens'
Getting the status of migrations:
# Tells you all migrations run
ActiveRecord::Migrator.get_all_versions
# Tells you the current schema version
ActiveRecord::Migrator.current_version
If you need more APIs for migrations or metadata see:
ActiveRecord::SchemaMigration
this is the ActiveRecord::Base class for the schema_migrations table
ActiveRecord::Migrator
where all the action happens when migrations are run

even if table is not exists:
model Kitten, expected table kittens
rails 3:
Kitten.table_exists? #=> false

I found this out while I was trying to remove a table via a migration:
drop_table :kittens if (table_exists? :kittens)
ActiveRecord::Migration.drop_table :kittens if (ActiveRecord::Base.connection.table_exists? :kittens)
works for Rails 3.2
This simpler form will become available in Rails 5:
drop_table :kittens, if_exists: true
Reference: https://github.com/rails/rails/pull/16366
And here's the Rails 5 ActiveRecord's CHANGELOG:
Introduce the :if_exists option for drop_table.
Example:
drop_table(:posts, if_exists: true)
That would execute:
DROP TABLE IF EXISTS posts
If the table doesn't exist, if_exists: false (the default) raises an exception whereas if_exists: true does nothing.

Rails 5.1
if ActiveRecord::Base.connection.data_source_exists? 'table_name'
drop_table :table_name
end
or
drop_table :table_name, if_exists: true

The proper way to do this is Model.table_exists?
class Dog < ApplicationRecord
# something
end
do_something if Dog.table_exists?

Related

rails test error:"table projectname_test.destroys doesn't exist"

I just started to learn Ruby on Rails. And when I used the rails to do the test, an error occurred as:
UserTest#test_the_truth:
ActiveRecord::StatementInvalid: Mysql2::Error: Table 'eula_test.destroys' doesn't exist: SHOW FULL FIELDS FROM destroys
I don't know what is eula_test.destroys and how should I solve this problem.
check your migration files. on db/migrate.rb and db/shema.rb you can check out if you have that table.
Seems no-one has been able to answer this, but best guess based on the error you are getting it looks like you need a join table because you most likely have a "has_and_belongs_to_many" directive in both your models eula.rb and test.rb
So you need to create a migration: rails g migration CreateEulaTest
then edit the migration to include an index that tells the db to look in eula_test table for the data to join with.
you need edit your migration with the following:
def up
create_table :eula_test, :id => false do |t|
t.integer :eula_id
t.integer :test_id
end
add_index(:eula_test, [:eula_id, :test_id]
end
def down
drop_table :eula_test
end
end
Note: this table does not require it's own ID hence the :id => false
Also, the add_index portion are your foreign keys between the 2 models that allows the database to know that you are going through the table to establish your directive, such as create and destroy etc.
run rails db:migrate for rails 5 or greater, rake db:migrate <5
You may need to check your models to ensure you have the correct has_to_and_belongs_to_many settings.
It is likely you missed this part of the tutorial. Some tutorials don't explain why things are done, they just show you the code and let you figure it out.
rails db:reset should fix it :)

Rails : Create a drop table cascade migration

How do I force a DROP TABLE CASCADE in a Rails 3.2 migration?
Is there an option to pass to drop_table("table_name")?
In Rails 4 you can do the following:
drop_table :accounts, force: :cascade
You could always run raw SQL in the migration.
MYSQL:
execute "DROP TABLE #{:table_name} CASCADE CONSTRAINTS PURGE"
PostgreSQL:
execute "DROP TABLE #{:table_name} CASCADE"
You can check the documentation of the built-in method drop_table here.
Put a file in your initializers directory called postgres.rb then did. This works for rails 4.1 anyway.
module ActiveRecord
module ConnectionAdapters # :nodoc:
module SchemaStatements
def drop_table(table_name, options = {})
execute "DROP TABLE #{quote_table_name(table_name)} CASCADE"
end
end
end
end

Alter Schema in Rails 2

I need to add some columns to a table in my schema. Can someone tell me the best way to do this?
The following seems incomplete or wrong since the schema.rb file did not update to include the new column and all of the corresponding view files (edit,index,new,show) did not update to include the new column. Not to mention the bloat of all of those migration classes that get generated. Thanks
ruby script/generate migration RecordLabelToAlbums record_label:string
exists db/migrate
create db/migrate/20121130125859_record_label_to_albums.rb
Creates this:
class RecordLabelToAlbums < ActiveRecord::Migration
def self.up
end
def self.down
end
end
I then added this:
class RecordLabelToAlbums < ActiveRecord::Migration
def self.up
add_column :albums, :record_label, :text
end
def self.down
remove_column :albums, :record_label
end
end
The I ran:
rake db:migrate
Got This:
Mysql::Error: Table 'albums' already exists: CREATE TABLE albums (id int(11) DEFAULT NULL auto_increment PRIMARY KEY, created_at datetime, updated_at datetime)
The code you added is correct.
The error suggests that for some reason your system appears to think it has not yet run the original migration that created the albums table. The state of migrations (in Rails 2) is specified in a table in the database called schema_migrations -- if this gets confused then it will try to re-run migrations. I am not sure what might cause it to get confused, but I do recall this happened a couple times back in 2008 when I was using Rails 2.x.
The table is simple -- you can see what's in it from a SQL prompt -- just the names of migrations it thinks it has run, I think.
If you don't mind losing some data, you can try rake db:rollback or even rake db:reset to get back to the beginning. rake db:rollback STEP=2 will rollback the last 2 migrations.
If you need the data, correct the contents of the table by adding one or more new records referencing the migrations in app/db/migrations that may have been missed. The order is important, I think (the format changed a little in Rails 3, I don't recall how).
Any time you want to add or change the database schema, use rails to generate a migration, and then run rake db:migrate once it's ready to go.
And just asking: is there any way you can move to Rails 3. It's been out for years now, and Rails 4 is coming soon. You'll find yourself in a backwater of incompatibilities, deprecations, security and performance issues and so on if you don't take the hit and upgrade.

Model.reset_column_information does not reload columns in rails migration

I'm using Rails 3.2 and have a migration that contains the code:
add_column :users, :gift_aid, :integer, :default => 2
# reset columns
User.reset_column_information
... code here to load legacy data from sqlite3 database ...
# now create a user with the loaded column data
user = User.create( ...other cols...,
:gift_aid => migrated_gift_aid_column_data,
...other cols... )
and I get unknown attribute: gift_aid when running the migration. User.column_names shows the same list before and after the call to reset_column_information.
Oddly when I manually drop the column in mysql and re-run the migration it works as expected. Starting from the first migration again with an empty database and it doesn't work so it's something to do with running all the migrations rather than the single one.
I have a couple of previous migrations on User model, both include reset_column_information and both work fine.
I'm really scratching my head on this one - anyone got any ideas
I think this must be some kind of bug related to schema caching... this might work:
User.connection.schema_cache.clear!
User.reset_column_information
(for Rails 3.2.2)
this isn't needed on rails 6 (tested on 6.0.0beta3).
I tried both with update!(new_column: ...) and update_all(new_column: ...)

Rails DB Migration - How To Drop a Table?

I added a table that I thought I was going to need, but now no longer plan on using it. How should I remove that table?
I've already run migrations, so the table is in my database. I figure rails generate migration should be able to handle this, but I haven't figured out how yet.
I've tried:
rails generate migration drop_tablename
but that just generated an empty migration.
What is the "official" way to drop a table in Rails?
You won't always be able to simply generate the migration to already have the code you want. You can create an empty migration and then populate it with the code you need.
You can find information about how to accomplish different tasks in a migration here:
http://api.rubyonrails.org/classes/ActiveRecord/Migration.html
More specifically, you can see how to drop a table using the following approach:
drop_table :table_name
Write your migration manually. E.g. run rails g migration DropUsers.
As for the code of the migration I'm just gonna quote Maxwell Holder's post Rails Migration Checklist
BAD - running rake db:migrate and then rake db:rollback will fail
class DropUsers < ActiveRecord::Migration
def change
drop_table :users
end
end
GOOD - reveals intent that migration should not be reversible
class DropUsers < ActiveRecord::Migration
def up
drop_table :users
end
def down
fail ActiveRecord::IrreversibleMigration
end
end
BETTER - is actually reversible
class DropUsers < ActiveRecord::Migration
def change
drop_table :users do |t|
t.string :email, null: false
t.timestamps null: false
end
end
end
First generate an empty migration with any name you'd like. It's important to do it this way since it creates the appropriate date.
rails generate migration DropProductsTable
This will generate a .rb file in /db/migrate/ like 20111015185025_drop_products_table.rb
Now edit that file to look like this:
class DropProductsTable < ActiveRecord::Migration
def up
drop_table :products
end
def down
raise ActiveRecord::IrreversibleMigration
end
end
The only thing I added was drop_table :products and raise ActiveRecord::IrreversibleMigration.
Then run rake db:migrate and it'll drop the table for you.
Warning: Do this at your own risk, as #z-atef and #nzifnab correctly point out, Rails will not be aware of these changes, your migration sequence fill fail and your schema will be different from your coworkers'. This is meant as a resource for locally tinkering with development only.
While the answers provided here work properly, I wanted something a bit more 'straightforward', I found it here: link
First enter rails console:
$rails console
Then just type:
ActiveRecord::Migration.drop_table(:table_name)
And done, worked for me!
You need to to create a new migration file using following command
rails generate migration drop_table_xyz
and write drop_table code in newly generated migration file (db/migration/xxxxxxx_drop_table_xyz) like
drop_table :tablename
Or if you wanted to drop table without migration, simply open rails console by
$ rails c
and execute following command
ActiveRecord::Base.connection.execute("drop table table_name")
or you can use more simplified command
ActiveRecord::Migration.drop_table(:table_name)
rails g migration drop_users
edit the migration
class DropUsers < ActiveRecord::Migration
def change
drop_table :users do |t|
t.string :name
t.timestamps
end
end
end
rake db:migrate
The simple and official way would be this:
rails g migration drop_tablename
Now go to your db/migrate and look for your file which contains the drop_tablename as the filename and edit it to this.
def change
drop_table :table_name
end
Then you need to run
rake db:migrate
on your console.
I wasn't able to make it work with migration script so I went ahead with this solution. Enter rails console using the terminal:
rails c
Type
ActiveRecord::Migration.drop_table(:tablename)
It works well for me. This will remove the previous table. Don't forget to run
rails db:migrate
I think, to be completely "official", you would need to create a new migration, and put drop_table in self.up. The self.down method should then contain all the code to recreate the table in full. Presumably that code could just be taken from schema.rb at the time you create the migration.
It seems a little odd, to put in code to create a table you know you aren't going to need anymore, but that would keep all the migration code complete and "official", right?
I just did this for a table I needed to drop, but honestly didn't test the "down" and not sure why I would.
you can simply drop a table from rails console.
first open the console
$ rails c
then paste this command in console
ActiveRecord::Migration.drop_table(:table_name)
replace table_name with the table you want to delete.
you can also drop table directly from the terminal. just enter in the root directory of your application and run this command
$ rails runner "Util::Table.clobber 'table_name'"
You can roll back a migration the way it is in the guide:
http://guides.rubyonrails.org/active_record_migrations.html#reverting-previous-migrations
Generate a migration:
rails generate migration revert_create_tablename
Write the migration:
require_relative '20121212123456_create_tablename'
class RevertCreateTablename < ActiveRecord::Migration[5.0]
def change
revert CreateTablename
end
end
This way you can also rollback and can use to revert any migration
Alternative to raising exception or attempting to recreate a now empty table - while still enabling migration rollback, redo etc -
def change
drop_table(:users, force: true) if ActiveRecord::Base.connection.tables.include?('users')
end
You can't simply run drop_table :table_name, instead you can create an empty migration by running:
rails g migration DropInstalls
You can then add this into that empty migration:
class DropInstalls < ActiveRecord::Migration
def change
drop_table :installs
end
end
Then run rails db:migrate in the command line which should remove the Installs table
The solution was found here
Open you rails console
ActiveRecord::Base.connection.execute("drop table table_name")
ActiveRecord::Base.connection.drop_table :table_name
if anybody is looking for how to do it in SQL.
type rails dbconsole from terminal
enter password
In console do
USE db_name;
DROP TABLE table_name;
exit
Please dont forget to remove the migration file and table structure from schema
I needed to delete our migration scripts along with the tables themselves ...
class Util::Table < ActiveRecord::Migration
def self.clobber(table_name)
# drop the table
if ActiveRecord::Base.connection.table_exists? table_name
puts "\n== " + table_name.upcase.cyan + " ! "
<< Time.now.strftime("%H:%M:%S").yellow
drop_table table_name
end
# locate any existing migrations for a table and delete them
base_folder = File.join(Rails.root.to_s, 'db', 'migrate')
Dir[File.join(base_folder, '**', '*.rb')].each do |file|
if file =~ /create_#{table_name}.rb/
puts "== deleting migration: " + file.cyan + " ! "
<< Time.now.strftime("%H:%M:%S").yellow
FileUtils.rm_rf(file)
break
end
end
end
def self.clobber_all
# delete every table in the db, along with every corresponding migration
ActiveRecord::Base.connection.tables.each {|t| clobber t}
end
end
from terminal window run:
$ rails runner "Util::Table.clobber 'your_table_name'"
or
$ rails runner "Util::Table.clobber_all"
Helpful documentation
In migration you can drop table by:
drop_table(table_name, **options)
options:
:force
Set to :cascade to drop dependent objects as well. Defaults to false
:if_exists
Set to true to only drop the table if it exists. Defaults to false
Example:
Create migration for drop table, for example we are want to drop User table
rails g migration DropUsers
Running via Spring preloader in process 13189
invoke active_record
create db/migrate/20211110174028_drop_users.rb
Edit migration file, in our case it is db/migrate/20211110174028_drop_users.rb
class DropUsers < ActiveRecord::Migration[6.1]
def change
drop_table :users, if_exist: true
end
end
Run migration for dropping User table
rails db:migrate
== 20211110174028 DropUsers: migrating ===============================
-- drop_table(:users, {:if_exist=>true})
-> 0.4607s
the best way you can do is
rails g migration Drop_table_Users
then do the following
rake db:migrate
Run
rake db:migrate:down VERSION=<version>
Where <version> is the version number of your migration file you want to revert.
Example:-
rake db:migrate:down VERSION=3846656238
Drop Table/Migration
run:-
$ rails generate migration DropTablename
exp:- $ rails generate migration DropProducts
if you want to drop a specific table you can do
$ rails db:migrate:up VERSION=[Here you can insert timestamp of table]
otherwise if you want to drop all your database you can do
$rails db:drop
Run this command:-
rails g migration drop_table_name
then:
rake db:migrate
or if you are using MySql database then:
login with database
show databases;
show tables;
drop table_name;
If you want to delete the table from the schema perform below operation --
rails db:rollback

Resources