I am trying to use Devise in my rails app but when I get to the point to migrate my database Devise gives me this error:
rake db:migrate
== 20141016065244 AddDeviseToPatients: migrating ==============================
-- change_table(:patients)
-> 0.0127s
-- add_index(:patients, :email, {:unique=>true})
rake aborted!
StandardError: An error has occurred, this and all later migrations canceled:
SQLite3::ConstraintException: UNIQUE constraint failed: patients.email: CREATE UNIQUE INDEX "index_patients_on_email" ON "patients" ("email")
I am trying to use devise in an already started project where the "User" table is called "Patient".
This is that table:
"Patient(id: integer, name: string, loginName: string, login: integer, created_at: datetime, updated_at: datetime)"
So what simple error am I making? :)
Here's the migration file: https://gist.github.com/macmattias/1c81717dbf218d18dc72
The field email is missing?
You need to add a field email to your table patients.
Related
I'm following along with the rails tutorial. I'm on ch. 6 and I'm getting a strange error with SQLite3 (for the record, I'm using sqlite version 1.3.10 and the tutorial uses 1.3.9)
I don't get an error when I run rake db:migrate, but when I run the migration for the test environment, here's what I get:
$ bundle exec rake test:models
rake aborted!
ActiveRecord::PendingMigrationError:
Migrations are pending. To resolve this issue, run:
bin/rake db:migrate RAILS_ENV=test
sample_app/test/test_helper.rb:3:in `<top (required)>'
sample_app/test/models/user_test.rb:1:in `require'
sample_app/test/models/user_test.rb:1:in `<top (required)>'
Tasks: TOP => test:models
(See full trace by running task with --trace)
$ bundle exec rake db:migrate RAILS_ENV=test
== 20150628011937 AddIndexToUsersEmail: migrating ===========================
==
-- add_index(:users, :email, {:unique=>true})
rake aborted!
StandardError: An error has occurred, this and all later migrations canceled:
SQLite3::ConstraintException: UNIQUE constraint failed: users.email: CREATE UNIQUE INDEX "index_users_on_email" ON "users" ("email")sample_app/db/migrate/20150628011937_add_index_to_users_email.rb:3:in `change'
C:in `migrate'
ActiveRecord::RecordNotUnique: SQLite3::ConstraintException: UNIQUE constrain
t failed: users.email: CREATE UNIQUE INDEX "index_users_on_email" ON "users"
("email")
sample_app/db/migrate/20150628011937_add_index_to_users_email.rb:3:in `change'
C:in `migrate'
SQLite3::ConstraintException: UNIQUE constraint failed: users.email
sample_app/db/migrate/20150628011937_add_index_to_users_email.rb:3:in `change'
C:in `migrate'
Tasks: TOP => db:migrate
(See full trace by running task with --trace)
Here is my user.rb model:
class User < ActiveRecord::Base
before_save { self.email = email.downcase }
validates :name, presence: true, length: { maximum: 50 }
VALID_EMAIL_REGEX = /\A[\w+\-.]+#[a-z\d\-.]+\.[a-z]+\z/i
validates :email, presence: true, length: { maximum: 255 },
format: { with: VALID_EMAIL_REGEX },
uniqueness: { case_sensitive: false }
end
Here is my most recent migration
class AddIndexToUsersEmail < ActiveRecord::Migration
def change
add_index :users, :email, unique: true
end
end
I can post any other files if those are relevant. Thanks in advance for the help!
The problem was that I had users in the database with the same email before the migration.
db:reset solved everything
I experienced it for a bit different reason and here is the solution.
For me the error was
Minitest::UnexpectedError: ActiveRecord::RecordNotUnique: SQLite3::ConstraintException: UNIQUE constraint failed: users.email: INSERT INTO "users" ("created_at", "updated_at", "id") VALUES ('2018-05-09 18:23:59.827561', '2018-05-09 18:23:59.827561', 298486374)
Notice the INTO "users" ("created_at", "updated_at", "id"). It was caused by test/fixtures/users.yml was not filled, so then there was duplicate values in columns which has unique key constraint.
test/fixtures/users.yml:
# Read about fixtures at http://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html
# This model initially had no columns defined. If you add columns to the
# model remove the '{}' from the fixture names and add the columns immediately
# below each fixture, per the syntax in the comments below
#
one: {}
# column: value
#
two: {}
# column: value
if you can't reset:db you should try to delete it by hand go to db folder and delete the "development.sqlite3" and the "test.sqlite3" files
then run
rails db:migrate
and bin/rails db:migrate RAILS_ENV=TEST
worked for me, anyway...
If this happens to you when running tests:
Make sure there are no users fixtures, unless you explicitly define those users with unique attributes.
test/fixtures/users.yml
When you generate a model, for example:
rails g model User
Rails automatically creates that file and it looks like:
# Read about fixtures at https://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html
# This model initially had no columns defined. If you add columns to the
# model remove the '{}' from the fixture names and add the columns immediately
# below each fixture, per the syntax in the comments below
#
one: {}
# column: value
#
two: {}
# column: value
This can mess up your tests.
Just use rake db:test:prepare and it will copy the dev database to test so you don't need to run the migrations.
I had to delete my development.db to resolve the issue.
I am going by this tutorial to create a small shopping cart system on rails:http://richonrails.com/articles/building-a-shopping-cart-in-ruby-on-rails
When I run:
rails g model Product name price:decimal{12,3} active:boolean
Then run the rake db:migrate but gives me the following error:
== 20150303175421 CreateProducts: migrating ===================================
-- create_table(:products)
rake aborted!
StandardError: An error has occurred, this and all later migrations canceled:
undefined method `decimal12' for #<ActiveRecord::ConnectionAdapters::TableDefinition:0x00000006a0fd10>/home/ubuntu/workspace/db/migrate/20150303175421_create_products.rb:5:in `block in change'
/usr/local/rvm/gems/ruby-2.1.5#rails4/gems/activerecord-4.1.6/lib/active_record/connection_adapters/abstract/schema_statements.rb:198:in `create_table'
Any help? Can't figure it out anywhere...
Thanks
As specified in documentation, you need to put the decimal field description in quotes otherwise rails gets confused and generates two fields.
rails g model Product name 'price:decimal{12,3}' active:boolean
undefined method `decimal12' for #
rails g model Product name 'price:decimal{12,3}' active:boolean
you need to pass it that way on your console: http://edgeguides.rubyonrails.org/active_record_migrations.html#creating-a-standalone-migration
I'm new to Ruby on Rails and I'm following the https://www.railstutorial.org/book/ guide to understand a bit more about it. I'm stuck at 6.3.3, where it tells to create a secure password. The previous migration seemed to have worked (to create a unique index and to create the secure password column). After that when i try to run:
rake test
it says that the test was aborted and that i should run:
rake db:migrate RAILS_ENV=test
but when i do run the command above it returns this:
c:\Sites\sample_app>rake db:migrate RAILS_ENV=test
DL is deprecated, please use Fiddle
== 20141226095217 AddIndexToUsersEmail: migrating =============================
-- add_index(:users, :email, {:unique=>true}) rake aborted! StandardError: An error has occurred, this and all later migrations canceled:
SQLite3::ConstraintException: indexed columns are not unique: CREATE UNIQUE INDEX "index_users_on_email" ON "users" ("email")c:/Si tes/sample_app/db/migrate/20141226095217_add_index_to_users_email.rb:3:in `change' C:in `migrate' Tasks: TOP => db:migrate (See full trace by running task with --trace)
I don't understand why this is happening. My DB is empty.
As requested, the migrations files:
20141226095217_add_index_to_users_email.rb
class AddIndexToUsersEmail < ActiveRecord::Migration
def change
add_index :users, :email, unique: true
end
end
20141226095746_add_password_digest_to_users.rb
class AddPasswordDigestToUsers < ActiveRecord::Migration
def change
add_column :users, :password_digest, :string
end
end
See https://stackoverflow.com/a/14765346/429758 for the exact same issue. As mentioned there, the issue is not with the migration, but with having duplicate values for email field in the users table.
Since this error is happening while running tests, it means the test database has duplicate emails for users.
Rails Tutorial book uses fixtures to setup test data. The test/fixtures/users.yml file used to create the users on test env is shown in Listing 6.29 as follows:
one:
name: MyString
email: MyString
two:
name: MyString
email: MyString
Both of these fixtures having MyString as email is what is causing the migration to fail. Change the values to make sure both have different values.
Example:
one:
name: First User
email: first#example.com
two:
name: Second User
email: second#example.com
EDIT
Looking back at the Rails Tutorial, the next step in Listing 6.30 is to empty the test/fixtures/users.yml file. That is another way to ensure this error does not occur.
I am new to both Ruby and Rails. So this may be an easy fix. I'm sorry if it is.
I recently installed Ruby-on-Rails and started following the tutorial on rubyonrails.org which shows how to make a simple blog. Everything was running fine until I got to section 5.5. I went to run db:migrate and it gave me an error.
|D:\Documents\Programs\Ruby\blog>rake db:migrate
== 20141216061542 CreateArticles: migrating ===================================
-- create_table(:articles)
rake aborted!
StandardError: An error has occurred, this and all later migrations canceled:
SQLite3::SQLException: table "articles" already exists: CREATE TABLE "articles" ("id" INTEGER
PRIMARY KEY AUTOINCREMENT NOT NULL, "title" varchar(255), "text" text, "created_at" datetime,
"updated_at"
datetime) D:/Documents/Programs/Ruby/blog/db/migrate/20141216061542_create_articles.rb:3:in
`change
'
C:in `migrate'
ActiveRecord::StatementInvalid: SQLite3::SQLException: table "articles" already exists: CREATE
TABLE
"articles" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "title" varchar(255), "text" text,
"created_at" datetime, "updated_at" datetime)
D:/Documents/Programs/Ruby/blog/db/migrate/20141216061542_create_articles.rb:3:in `change'
C:in `migrate'
SQLite3::SQLException: table "articles" already exists
D:/Documents/Programs/Ruby/blog/db/migrate/20141216061542_create_articles.rb:3:in `change'
C:in `migrate'
Tasks: TOP => db:migrate
(See full trace by running task with --trace)
I fired up the server to see what it would show and it gave me this:
ActiveRecord::PendingMigrationError
Migrations are pending. To resolve this issue, run: bin/rake db:migrate RAILS_ENV=development
It's been doing this ever since. I have tried starting over by deleting the project.(not entirely sure if that was a good move.) I have tried looking over the code. Nothing I have tried has given me any hints on what to do.
Is there any way to get rid of these errors?
Thank you in advance.
EDIT:
I tried to reset the database with 'rake db:reset', but it just gave me this:
|D:\Documents\Programs\Ruby\blog\app\views\articles>rake db:reset
(in D:/Documents/Programs/Ruby/blog)
Permission denied # unlink_internal - D:/Documents/Programs/Ruby/blog/db/development.sqlite3
C:/RailsInstaller/Ruby2.1.0/lib/ruby/2.1.0/fileutils.rb:1460:in `unlink'
C:/RailsInstaller/Ruby2.1.0/lib/ruby/2.1.0/fileutils.rb:1460:in `block in remove_file'
C:/RailsInstaller/Ruby2.1.0/lib/ruby/2.1.0/fileutils.rb:1468:in `platform_support'
...
rake aborted!
Errno::EACCES: Permission denied # unlink_internal -
D:/Documents/Programs/Ruby/blog/db/development.
sqlite3
Tasks: TOP => db:schema:load
(See full trace by running task with --trace)
I shortened it for readability.
And here is my create_articles migration file:
class CreateArticles < ActiveRecord::Migration
def change
create_table :articles do |t|
t.timestamps
end
end
end
You've already created that particular table. Try this from your terminal:
rake db:drop db:create db:migrate
Or:
rake db:reset db:migrate
So basically, you will start your database from scratch, which will avoid the current error.
Note that for new migrations, you only run the 'rake db:migrate' command otherwise your existing data will be lost.
Later on if you come across this problem in a production environment, ensure that you do 'something else' - surely you wouldn't want to sacrifice your production database data.
Well It seems obvious, you already have table articles, and you are trying to create a new one.
Two options:
comment migration with articles do rake db:migrate, uncomment for other environment (if any)
clear database and run migrations again.
Add create_articles to your question as well, could help resolving the problem.
Drop the db
rake db:drop
And Migrated it once again
rake db:migrate
You have already create articles tables. So you need to drop it and migrate it once again.
When I try to run migration for this file:
class AddIndexToUsernameDowncaseForUsers < ActiveRecord::Migration
def up
execute 'CREATE INDEX index_users_on_username_downcase ON users (lower(username));'
end
def down
remove_index :users, name: :index_users_on_username_downcase
end
end
I get this error:
== 20140521043803 AddIndexToUsernameDowncaseForUsers: migrating ===============
-- execute("CREATE INDEX index_users_on_username_downcase ON groups lower(username);")
rake aborted!
StandardError: An error has occurred, this and all later migrations canceled:
undefined method ` execute' for #<AddIndexToUsernameDowncaseForUsers:0x007fea8a9b9c50>/Users/mydir/db/migrate/20140521043803_add_index_to_username_downcase_for_users.rb:3:in `up'
NoMethodError: undefined method ` execute' for #<AddIndexToUsernameDowncaseForUsers:0x007fea8a9b9c50>
/Users/mydir/db/migrate/20140521043803_add_index_to_username_downcase_for_users.rb:3:in `up'
I'm really confused as I've never had issues running migrations before. It looks like the helpers aren't getting included or something. Pretty stumped, but my guess is this is a facepalm-level issue by me.
Rails 4.1.1, Ruby 2.1.1, Postgres 9.3
There are 4 unprintable characters before the word execute - it shows both when it echoes the statement during the migration and also within the quotes in the error: ' execute'.
So it's actually looking for a method called ....execute where .... are those characters.