Under what circumstances would this happen in rails (db)? - ruby-on-rails

Utterly confused at this mess:
rake db:drop
>
rake db:create
> my_database already exists
rake db:migrate
> unknown database my_database
Appreciate any insight.

That's because first time when u do rake db:create it creates two databases one is development and other is test. then when u do rake db:drop it drops the database, but it only drops the development database not the test database. so try removing the test database explicitly and everything should be fine.

Try :
rake db:drop
rake db:create RAILS_ENV=development
rake db:migrate RAILS_ENV=development
if getting same error then open mysql terminal and create database manually :
CREATE DATABASE database_name;
then run
rake db:migrate

Related

Is there a way to run rake db:setup on a single table?

I have a Ruby on rails app, and I modified db/seeds.rb file and I want to push my changes into my database.
is there an option in Rails where I can run rake db:setup and modify only that table without clearing all the other ones ?
Thanks
You use rake db:seed to run the seed file. rake db:setup is much more involved, it basically runs all of the following
db:create
db:schema:load
db:seed

why does rake db:migrate say my development database doesn't exist?

I'm typing in the terminal
rake db:migrate
Here's the error Im getting
ActiveRecord::NoDatabaseError: FATAL: database "db/development.sqlite3" does not exist
rake db:migrate doesn't create database, rather requires it exists.
rake db:create creates a database without loading database schema.
Remember you should run rake db:create before you can run rake db:migrate if you dropped database with rake db:drop.

Migrations are pending; run 'bin/rake db:migrate RAILS_ENV=development' to resolve this issue [unable to proceed]

I appear to have a circular issue in regards to Ruby on Rails migration procedure. I am following the introduction article and I have reached the point when I need to create my first table.
I have ran the following,
[tims#web2 working_ror]# rails generate model Homepage first_name:string last_name:string email:string message:text
invoke active_record
create db/migrate/20131119203948_create_homepages.rb
create app/models/homepage.rb
invoke test_unit
createtest /models/homepage_test.rb
createtest /fixtures/homepages.yml
I then proceeded with the migration,
[tims#web2 working_ror]# rake db:migrate
== CreateHomepages: migrating ================================================
-- create_table(:homepages)
-> 0.0493s
== CreateHomepages: migrated (0.0494s) =======================================
, however, when I run my application I see the following message,
Migrations are pending; run 'bin/rake db:migrate RAILS_ENV=development' to resolve this issue.
but, IF I run the above,
[tims#web2 working_ror]# rake db:migrate RAILS_ENV=development
[tims#web2 working_ror]#
and the message continues ...
I have spent considerable amount of time researching forums in-which the closest I could find was to drop and re-build everything, which have done the following.
rake db:drop
rake db:create
rake db:migrate
and the results are the same.
You need to do
bundle exec rake test:prepare
or
bundle exec rake db:test:prepare
and then
bundle exec rake db:migrate
before running the specs
Cheers
cited from : Why am I asked to run 'rake db:migrate RAILS_ENV=test'?
you can do
bundle exec rake test:prepare
In Rails 4.1+, they deprecated db:test:prepare
You can now just use:
ActiveRecord::Migration.maintain_test_schema!
If you need to do it manually
rake db:schema:load RAILS_ENV=test
and then
bundle exec rake db:migrate
try
In RAILS_ROOT/config/environments/development.rb Set the following setting to false:
config.active_record.migration_error = false#:page_load
One weird trick that you can use when your migrations are screwed (file deleted, manually renamed, etc.)
Fire up your favourite DB admin tool (eg. PGAdmin3) and browse to the database in question.
Look for a table called schema_migrations and browse its content. It should have a single column called version. This field is used by Rails to check whether migrations are up to date.
Make sure that your migration timestamps corresponds with the data in this column. If you have deleted an older migration, delete the corresponding timestamp.
Check to make sure that table doesn't already exist:
type - rails dbconsole
type - .tables (check to see if there was an error during the rake db:migrate that has the table name like -- create_table(:test) rake aborted!)
If you see the table name after running the .tables in the console type - drop table TABLENAME;
Then .quit to go back to the branch and run the rake db:migrate command again.
this was what i did:
rails db:environment:set RAILS_ENV=test
If you need to do it manually
rake db:schema:load RAILS_ENV=test
and then
bundle exec rake db:migrate
Thanks to Ahmed Ali....... your comment was helpful.

Want to re-create table when running rake db:seed

I want to remove all tables and re-created the db when I run
rake db:create
The reason is the id's on the tables are not set to 1, so I figured i can just re-create the db if its possible, or call truncate.
rake db:reset
may be what you are looking for. or...
rake db:drop
rake db:create
Try rake db:reset (in Rails 3)
In Rails 2, maybe this will help: http://pivotallabs.com/users/alex/blog/articles/305-collapsing-migrations

Purge or recreate a Ruby on Rails database

I have a dev Ruby on Rails database full of data. I want to delete everything and rebuild the database. I'm thinking of using something like:
rake db:recreate
Is this possible?
I know two ways to do this:
This will reset your database and reload your current schema with all:
rake db:reset db:migrate
This will destroy your db and then create it and then migrate your current schema:
rake db:drop db:create db:migrate
All data will be lost in both scenarios.
On Rails 4, all needed is
$ rake db:schema:load
That would delete the entire contents on your DB and recreate the schema from your schema.rb file, without having to apply all migrations one by one.
I use the following one liner in Terminal.
$ rake db:drop && rake db:create && rake db:migrate && rake db:schema:dump && rake db:test:prepare
I put this as a shell alias and named it remigrate
By now, you can easily "chain" Rails tasks:
$ rake db:drop db:create db:migrate db:schema:dump db:test:prepare # db:test:prepare no longer available since Rails 4.1.0.rc1+
Update: In Rails 5, this command will be accessible through this command:
rails db:purge db:create db:migrate RAILS_ENV=test
As of the newest rails 4.2 release you can now run:
rake db:purge
Source: commit
# desc "Empty the database from DATABASE_URL or config/database.yml for the current RAILS_ENV (use db:drop:all to drop all databases in the config). Without RAILS_ENV it defaults to purging the development and test databases."
task :purge => [:load_config] do
ActiveRecord::Tasks::DatabaseTasks.purge_current
end
It can be used together like mentioned above:
rake db:purge db:create db:migrate RAILS_ENV=test
Depending on what you're wanting, you can use…
rake db:create
…to build the database from scratch from config/database.yml, or…
rake db:schema:load
…to build the database from scratch from your schema.rb file.
From the command line run
rake db:migrate:reset
In Rails 6 there is a convenient way for resetting DB and planting seeds again:
rails db:seed:replant # Truncates tables of each database for current environment and loads the seeds
https://weblog.rubyonrails.org/2019/3/15/this-week-in-rails-security-fixes-bulk-insert-and-upsert-seeds-replanting/
Use like
rake db:drop db:create db:migrate db:seed
All in one line. This is faster since the environment doesn't get reloaded again and again.
db:drop - will drop database.
db:create - will create database (host/db/password will be taken from config/database.yml)
db:migrate - will run existing migrations from directory (db/migration/.rb)*.
db:seed - will run seed data possible from directory (db/migration/seed.rb)..
I usually prefer:
rake db:reset
to do all at once.
Cheers!
Just issue the sequence of the steps: drop the database, then re-create it again, migrate data, and if you have seeds, sow the database:
rake db:drop db:create db:migrate db:seed
Since the default environment for rake is development, in case if you see the exception in spec tests, you should re-create db for the test environment as follows:
RAILS_ENV=test rake db:drop db:create db:migrate
In most cases the test database is being sowed during the test procedures, so db:seed task action isn't required to be passed. Otherwise, you shall to prepare the database:
rake db:test:prepare
or
RAILS_ENV=test rake db:seed
Additionally, to use the recreate task you can add into Rakefile the following code:
namespace :db do
task :recreate => [ :drop, :create, :migrate ] do
if ENV[ 'RAILS_ENV' ] !~ /test|cucumber/
Rake::Task[ 'db:seed' ].invoke
end
end
end
Then issue:
rake db:recreate
You can manually do:
rake db:drop
rake db:create
rake db:migrate
Or just rake db:reset, which will run the above steps but will also run your db/seeds.rb file.
An added nuance is that rake db:reset loads directly from your schema.rb file as opposed to running all the migrations files again.
You data gets blown away in all cases.
You can use this following command line:
rake db:drop db:create db:migrate db:seed db:test:clone
To drop a particular database, you can do this on rails console:
$rails console
Loading development environment
1.9.3 > ActiveRecord::Migration.drop_table(:<table_name>)
1.9.3 > exit
And then migrate DB again
$bundle exec rake db:migrate
On rails 4.2, to remove all data but preserve the database
$ bin/rake db:purge && bin/rake db:schema:load
https://github.com/rails/rails/blob/4-2-stable/activerecord/CHANGELOG.md
You can use
db:reset - for run db:drop and db:setup or
db:migrate:reset - which runs db:drop, db:create and db:migrate.
dependent at you want to use exist schema.rb
According to Rails guide, this one liner should be used because it would load from the schema.rb instead of reloading the migration files one by one:
rake db:reset
Because in development , you will always want to recreate the database,you can define a rake task in your lib/tasks folder like that.
namespace :db do
task :all => [:environment, :drop, :create, :migrate] do
end
end
and in terminal you will run
rake db:all
it will rebuild your database
3 options, same result:
1. All steps:
$ rake db:drop # deletes the database for the current env
$ rake db:create # creates the database for the current env
$ rake db:schema:load # loads the schema already generated from schema.rb / erases data
$ rake db:seed # seed with initial data
2. Reset:
$ rake db:reset # drop / schema:load / seed
3. Migrate:reset:
$ rake db:migrate:reset # drop / create / migrate
$ rake db:seed
Notes:
If schema:load is used is faster than doing all migrations, but same result.
All data will be lost.
You can run multiple rakes in one line.
Works with rails 3.
I think the best way to run this command:
**rake db:reset** it does db:drop, db:setup
rake db:setup does db:create, db:schema:load, db:seed
Simply you can run
rake db:setup
It will drop database, create new database and populate db from seed if you created seed file with some data.
I use:
rails db:drop to delete the databases.
rails db:create to create the databases based on config/database.yml
The previous commands may be replaced with rails db:reset.
Don't forget to run rails db:migrate to run the migrations.
I've today made quite a few changes to my rails schema. I realised I needed an additional two models in a hierarchy and some others to be deleted. There were many little changes required to the models and controllers.
I added the two new models and created them, using:
rake db:migrate
Then I edited the schema.rb file. I manually removed the old models that were no longer required, changed the foreign key field as required and just reordered it a bit to make it clearer to me. I deleted all the migrations, and then re-ran the build via:
rake db:reset
It worked perfectly. All the data has to be reloaded, of course. Rails realised the migrations had been deleted and reset the high-water mark:
-- assume_migrated_upto_version(20121026094813, ["/Users/sean/rails/f4/db/migrate"])
TL;DR - I use this rake script during development to blow away everything, including the schema file, then rebuild directly from migration scripts. It rebuilds both dev and test databases simultaneously. It's the only way I've found to guarantee everything lines up the way I expect. Been using it for years without a problem.
# lib/tasks/db_rebuild.rake
require 'fileutils'
namespace :db do
desc "Create DB if it doesn't exist, then migrate and seed"
task :build do
Rake::Task["db:create"].invoke
Rake::Task["db:migrate"].invoke
Rake::Task["db:seed"].invoke
end
desc "Drop database and rebuild directly from migrations (ignores schema.rb)"
task :rebuild do
raise "Task not permitted in production." if ENV["RAILS_ENV"] == "production"
puts "*** Deleting schema.rb"
system "rm -f #{Rails.root.join("db", "schema.rb")}"
puts "*** Deleting seed lock files"
system "rm -f #{Rails.root.join("db", ".loaded*")}"
puts "*** Recreate #{ENV['RAILS_ENV']} database"
begin
Rake::Task['environment'].invoke
ActiveRecord::Base.connection
rescue ActiveRecord::NoDatabaseError
# database doesn't exist yet, just create it.
Rake::Task["db:build"].invoke
rescue Exception => e
raise e
else
Rake::Task["db:environment:set"].invoke
# https://github.com/rails/rails/issues/26319#issuecomment-244015760
# ENV["DISABLE_DATABASE_ENVIRONMENT_CHECK"] = '1'
Rake::Task["db:drop"].invoke
Rake::Task["db:build"].invoke
end
Rake::Task["db:retest"].invoke
end
desc "Recreate the test DB"
task :retest do
system("rake db:drop db:build RAILS_ENV=test")
end
end
Rationale - The problem with all the provided solutions is that native Rake tasks provided by Rails rely on schema.rb. When I am doing heavy data modeling, I make changes directly to the migration files; only after they've been committed upstream do we treat them as immutable. But if I make changes to the migration file, they aren't reflected in schema.rb.
The other problem is the distinction between dev and test environments. Rails db tasks handle them independently, but in my experience dev and test databases should always maintain parity, which means I had to run lots of duplicative database cleanup when developing.

Resources