Why record does not go into rails test database - ruby-on-rails

class CreateUsers < ActiveRecord::Migration
def change
create_table :users do |t|
t.string :name
t.timestamps
end
# Create sample User
User.create :name => "TestUser"
end
end
When run rake db:create and rake db:migrate command
In development database it creates sample user but not in test database. I want this user in test database also. any reason?
Also tried rake db:migrate RAILS_ENV=test.

First you should run the following command rake db:test:prepare in order to "prepare" the test database.
Finally, I recommend using the following file db/seeds.rb if you wish to add new records in your database.
In the db/seeds.rb file:
User.create(name: "TestUser")
Run:
rake db:seed
rake db:seed RAILS_ENV=test # for test env

If you're looking to test a user why not create a fixture or use rspec for testing something like this? The above code is bad practice. I would do something like this
migration file.
def self.up
create_table :users do |t|
t.string :name
t.timestamps
end
end
Depending on your testing stack I would setup a fixture like so(yml fixture)
david:
name: David Smith
You could also use rspec with factory girl which makes testing alot easier in rails.

Related

bundle exec rake db:migrate worked, but development.sqlite3 is empty

I'm new to RoR. The following line executed normally:
bundle exec rake db:migrate
Output showed that it is migrated. development.sqlite3 and production.sqlite3 were created but empty, although schema.rb was written properly. The users table was successfully created, but without any records. Also I executed:
bundle exec rake db:test:prepare
test.sqlite3 is created and also written properly. This is the content of the file inside the migration file:
class CreateUsers < ActiveRecord::Migration
def change
create_table :users do |t|
t.string :name
t.string :email
t.timestamps
end
end
end
Kindly help me solve the problem. Let me know if any other details need to be specified.
So bundle exec rake db:test:prepare probably sets your environment to test.
That would be the reason why you'll end up with a working test database.
If you want to have the data in the development database, you need to set the environment to development.
Try RACK_ENV=development bundle exec rake db:test:prepare.
Although the cleaner solution is to create a seed file. See: http://edgeguides.rubyonrails.org/active_record_migrations.html#migrations-and-seed-data

Error ActiveRecord::PendingMigrationError

I am following Michael Hartl's book and I am getting this error when I run the server:
I am getting ActiveRecord::PendingMigrationError when I run the server, this shows up:
Migrations are pending. To resolve this issue, run: bin/rails db:migrate RAILS_ENV=development
Please I've been stuck in this error for so long.
When I type $ RAILS_ENV=development rake db:migrate I get this error:
== 20161209073230 AddActivationToUsers: migrating =============================
-- add_column(:users, :activation_digest, :string) rake aborted! StandardError: An error has occurred, this and all later migrations
canceled:
SQLite3::SQLException: duplicate column name: activation_digest: ALTER
TABLE "users" ADD "activation_digest" varchar
(required)>' Tasks: TOP => db:migrate (See full trace by running task
with --trace)
test/mailers/previews/user_mailer_preview.rb
UserMailerPreview < ActionMailer::Preview
# Preview this email at
http://localhost:3000/rails/mailers/user_mailer/account_activation
def account_activation
user = User.first
user.activation_token = User.new_token
UserMailer.account_activation(user) end
# Preview this email at
http://localhost:3000/rails/mailers/user_mailer/password_reset def
password_reset
UserMailer.password_reset end
end
Schema.rb:
# This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
#
# Note that this schema.rb definition is the authoritative source for your
# database schema. If you need to create the application database on another
# system, you should be using db:schema:load, not running all the migrations
# from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema.define(version: 20161123005710) do
create_table "users", force: :cascade do |t|
t.string "name"
t.string "email"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "password_digest"
t.string "remember_digest"
t.string "activation_digest"
t.index ["email"], name: "index_users_on_email", unique: true end
end
Latest migration is
db/migrate/[timestamp]_add_activation_to_users.rb:
class AddActivationToUsers < ActiveRecord::Migration[5.0]
def change
add_column :users, :activation_digest, :string
add_column :users, :activated, :boolean, default: falserao
add_column :users, :activated_at, :datetime
end
end
The correct command to apply unapplied migrations is RAILS_ENV=development rake db:migrate
This just means that you have a migration pending. When you create a new migration
railas g migration MigrationName
it means that it changes something in the database schema or the layout of your database. In order to commit that change, you have to run:
bin/rails db:migrate
This will look into your migration file and apply it to your databse. Once the migration is done, you can run server as usual again.
rails server
If you have more question, I recommend reading the migration documentation that Rails published:
http://guides.rubyonrails.org/active_record_migrations.html
SQLite3::SQLException: duplicate column name: activation_digest:
(The following is the SQL command that actually modifies the db):
ALTER TABLE "users" ADD "activation_digest"
The SQL command reads like plain English. Somehow one of your migrations is doing something a previous migration already did, namely adding the activation_digest column to your users table in the db. If you look in the directory db/migrate/, you will see all your migration files. If you open one of them up, you should sort of be able to tell what it is doing. So look at all your migration files and find the two migrations that both add the activation_digest column. If the two migration files are identical, then you need to delete one--but take the following steps before deleting a migration:
https://www.baserails.com/questions/i-messed-up-while-generating-my-migration-how-can-i-undo-it
Also check out the section Rolling Back in the Rails Guide:
http://edgeguides.rubyonrails.org/active_record_migrations.html#reverting-previous-migrations
If for some reason you don't have two identical migration files that both add the activation_digest column, e.g one of the migration files does something additionally, then you need to figure out what steps in the tutorial that you did wrong, then rollback to the last migration that you know is correct. Finally, follow the steps in the tutorial again for generating the subsequent migrations.
It seems your users table already have a column named activation_digest. Remove the add_column line where the column is added from the migration file and run the migration again.
I think this migration file should work:
class AddActivationToUsers < ActiveRecord::Migration[5.0]
def change
add_column :users, :activated, :boolean, default: false
add_column :users, :activated_at, :datetime
end
end
Ok the answer is very simple!Just try migrating your DB to version=0 with command: rake db:migrate VERSION=0
and then run rake db:migrate

Rails 4 Migration Error (Can't rake db:migrate) SQLite3::SQLException: duplicate column name

I've been trying to get the Paperclip gem working. The problem that I was initially running into was that pictures were getting uploaded but not displaying. I then messed around with the database by doing a rake db:rollback to try and fix the error. Now I can't rake db:migrate again because of this error
SQLite3::SQLException: duplicate column name: image_file_name: ALTER TABLE "posts" ADD "image_file_name" varchar
I've personally went into the migration folder and deleted the file to try and generate a migration again. I've been trying to do rails generate paperclip post image and it does create a migration file, but I'm unable to rake db:migrate.
Any suggestions?
Thanks!
Deleting a migration file doesn't really rollback the change it made in your database. Your best bet is to:
Don't delete the migration but comment out the content of the migration class, and run rake db:migrate,
Let's say I have this as my migration file
class AddEmailSentToNeeds < ActiveRecord::Migration
def change
add_column :needs, :email_sent, :boolean ,default: false
end
end
Just comment out the method but leave the class, so it would be:
class AddEmailSentToNeeds < ActiveRecord::Migration
# def change
# add_column :needs, :email_sent, :boolean ,default: false
# end
end
This is just a hacky way to tell rails to skip this migration.
OR
start from the start so go do, rake db:drop, rake db:create, and rake db:migrate

What to do after a failed heroku db:rollback

I'm at the very beginning stages of learning rails using heroku as deployment tool. I ran into a bit of problem today, which is now fixed, but I was wondering if there's a proper/better way to do what I did.
My problem was as follows: I wrote a migration file that created a table with some indices (using add_index). The code would look like this:
class DeviseCreateUsers < ActiveRecord::Migration
def change
create_table(:users) do |t|
t.string :username
...
end
add_index :users, :username, :unique => true
end
def self.down
drop_table(:users)
remove_index :users, :username
end
end
heroku run rake db:migrate ran fine but heroku run rake db:rollback failed because (I assume) remove_index was trying to delete an index from a column that had already been erased.
So I then added a self.down method to my migration file (removing the indices before dropping the table). Afterwards, heroku run rake db:migrate didn't do anything, and heroku run rake db:rollback is stuck at the same error as before. Resetting the database or dropping the table didn't work either. I ended up removing the add_index lines in my migration before the rollback finally works.
... and unfortunately I no longer have any idea why db:rollback failed. The error message was 'index_users_on_username' on table 'users' does not exist', so my guess is that I did something stupid like modifying the database or modified the migration file before doing a rollback. Or could it be because I am mixing change and down method in the same migration file?
Anyway, my main question is, if a db:rollback fails, what then?
Some options in my head:
Fix the migration file until the rollback works
Fix the database manually until the rollback works
Fix the database manually and ignore the migration completely (dunno how to do this)
this)
???

new to rails, setting up db then running rake db:create/migrate

hi im currently learning rails, and following a tutorial. the instructions were to edit the migration file after i've created the app, then running rake db:migrate, then rake db:create.
i've edited the migration file to this:
class CreateUsers < ActiveRecord::Migration
def change
create_table :users do |t|
t.string :username
t.string :email
t.string :encrypted_password
t.string :salt
t.timestamps
end
end
end
then when i've run 'rake db:migrate' i got an error
Mysql2::Error: Table 'users' already exists: CREATE TABLE `users` ...
after i'm supposed to run 'rake db:create', then im getting this
user_auth_development already exists
user_auth_test already exists
You run rake db:create once and only once, and you run it first. Then you run rake db:migrate every time you add/change a migration. You've either already run this migration, or you are pointing at a database that already exists and already contains a table named users. My guess is that you ran the migration once already, in which case you're probably good to go. If you want to nuke the DB and start over, do rake db:drop db:create db:migrate.
We can simply give, it will do all the rake task which is require for database creation and migration
rake db:setup
For Rails 5 and 6, the command is:
rails setup
This will "create the database, load the schema, and initialize it with the seed data" (docs).
For rails 6 & above, you can give this command to create a database, migrate all the migration files, and seed the data into the database:
rails db:prepare

Resources