rake db:migrate alter table name - ruby-on-rails

I wanted to change the name of a table I creted with rake db:migrate from financialss to financials. I created a file in my migrate directory called changeme.rb that looks like this.
class CreateFinancials < ActiveRecord::Migration
def self.up
rename_table :financials, :financialss
end
def self.down
rename_table :financialss, :financials
end
end
I tried to run the following:
rake db:migrate:up changeme.rb
and got the following error:
rake aborted!
Don't know how to build task 'db:migrate:changeme.rb'
All help appreciated

Use the rails generator
rails g migration MigrationName
The rails do not understand when you come out of the convention. So try to use the default generator.

Related

NameError: uninitialized constant Model - rake db:migrate

I'm trying to migrate a change to my Comments table with rails migration. I've already made the migration and everything looks good but when I run rake db:migrate it sends back this error NameError: uninitialized constant Model. I can't see the problem? All the naming look right to me. Here is my migration file let me know if anything looks off or if you need more information. Thank you!
MIGRATION:
class AddColumnToComments < ActiveRecord::Migration
def change
add_column :comments, :fav_drink, :string
add_column :comments, :visit_time, :string
end
end
ERROR:
I assume you've used rails generator to create your migration and this generator has probably create a migration file named: 201606xxxxxxxx_model.rb.
If it's the case, rename you migration file as follow: 201606xxxxxxxx_add_column_to_comments.rb

Irreversible migration, can it be fixed? - Rails 4

So i made a migration like this
class AddDatetimeAttrToUsers < ActiveRecord::Migration
def change
change_column :users, :oauth_expires_at, :datetime
end
end
on my local environment it works just fine but when i try
heroku run rake db:migrate i get an error
ERROR: column "oauth_expires_at" cannot be cast automatically to type timestamp without time zone
HINT: Specify a USING expression to perform the conversion.
When i searched it, i created a new migration like this as best practice for changing an attribute using change.
class PutDatetimeFieldToUsersExpireAtColumn < ActiveRecord::Migration
def change
remove_column :users, :oauth_expires_at
add_column :users, :oauth_expires_at, :datetime
end
end
so i tried to use rake db:rollback to delete last migration and add this one informing me that the last migration is irreversible.
my question is, is there a way to actually rollback on an irreversible migration or should i just migrate using the new migration above?
In your example, you have the following migration file:
class AddDatetimeAttrToUsers < ActiveRecord::Migration
def change
change_column :users, :oauth_expires_at, :datetime
end
end
You have already run rake db:migrate successfully in your dev environment. You are running sqlite3 locally and PG on heroku, and and as a result, your change_column works locally, but it fails on PG because PG expects a 'using' statement.
The fix this, step 1 is to edit your migration file to add an up and down migration as suggested by Yohann above. Yes, you should do this even though you have already raked this migration.
class AddDatetimeAttrToUsers < ActiveRecord::Migration
def up
change_column :users, :oauth_expires_at, :datetime
end
def down
change_column :users, :oauth_expires_at, :time (or whatever type existed before datetime)
end
end
Now you can run rake db:rollback and avoid the irreversible migration error, but only if you HAVE NOT ADDED ADDITIONAL MIGRATIONS. If you have added additional migrations you will need to specify how far back to go using rake db:down VERSION=2018xxxxxxx or rake db:rollback STEP=X.
Now edit the migration so it plays nice with pg and sqlite3:
class AddDatetimeAttrToUsers < ActiveRecord::Migration
def up
change_column :users, :oauth_expires_at, :datetime, using: 'oauth_expires_at::datetime'
end
def down
change_column :users, :oauth_expires_at, :time
end
Now you should be able to rake db:migrate, push to heroku, and heroku run rake db:migrate and move on.
Finally, you should get pg working locally to match your production environment.
You can define up and down methods instead of change in your migration.
Here is an example:
def up
connection.execute %(create or replace view name_of_the_db_view)
end
def down
connection.execute %(drop view name_of_the_db_view)
end
With it you will be able to migrate and rollback the previously irreversible migration like it was a normal migration.
It seems you need to specify a current type of oauth_expires_at column, because at rollback Rails should know it to create the column. I mean following:
remove_column :users, :oauth_expires_at, :string
if you dare to lose your data on your local database then you can recover from irreversible migration(by losing your database data) by doing these steps:
1- first deleting your database(assuming that you are in the development environment and just ok to delete the database in this environment - your test database will also be gone)
export RAILS_ENV=development
rake db:drop
2- Reloading your schema file:
rake db:schema:load
3- To see your current migration files:
rake db:migrate:status
4- Delete the migration that you want to get rid of:
rake db:migrate:down VERSION=xxxxxx
rails destroy migration migration_name
5- Then you can make db:migrate to migrate your migrations.
rake db:migrate

Schema file does not reflect table removal migrations

I removed several tables in my Rails database by running rails generate migration RemoveObjects and then ran rake db:migrate to complete the migration, however I am not seeing the change reflected in my schema.rb file.
What else should I do to remove references to these object from that file?
Try this :
rake db:schema:dump
This migration will! You probably made a mistake inside the migration itself.
class DropTables < ActiveRecord::Migration
def up
drop_table :table_name
end
def down
raise ActiveRecord::IrreversibleMigration
end
end

Rake is out of synch with my Database

I have inherited a Ruby on Rails project where the programmer didn't use rake to create the db schema, so it seems very out of synch, is there a way to rectify this?
First create a schema.rb file
rake db:schema:dump
Then make a migration ot of it.
class CreateMigration < ActiveRecord::Migration
def self.up
# insert schema.rb here
end
def self.down
end
end
You might also need to create the schema_migrations table, and manually add the timestamp for this migration to it.

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