issues with installing devise - ruby-on-rails

here's my current user schema:
# == Schema Information
#
# Table name: users
#
# id :integer not null, primary key
# first_name :string
# last_name :string
# created_at :datetime not null
# updated_at :datetime not null
#
require 'elasticsearch/model'
class User < ActiveRecord::Base
searchkick word_start: [:user]
has_many :posts
validates :first_name, :last_name, presence: true
end
these are the steps I'm able to go through before the problem rears its head:
rails generate devise:install
rails generate devise user
rake db:migrate
once i try to migrate it, this is what comes up:
== 20160707230510 AddDeviseToUsers: migrating =================================
-- change_table(:users)
rake aborted!
StandardError: An error has occurred, this and all later migrations canceled:
PG::DuplicateColumn: ERROR: column "email" of relation "users" already exists
: ALTER TABLE "users" ADD "email" character varying DEFAULT '' NOT NULL
/Users/aa/Documents/railsy/basicProject/db/migrate/20160707230510_add_devise_to_users.rb:5:in `block in up'
/Users/aa/Documents/railsy/basicProject/db/migrate/20160707230510_add_devise_to_users.rb:3:in `up'
ActiveRecord::StatementInvalid: PG::DuplicateColumn: ERROR: column "email" of relation "users" already exists
: ALTER TABLE "users" ADD "email" character varying DEFAULT '' NOT NULL
/Users/aa/Documents/railsy/basicProject/db/migrate/20160707230510_add_devise_to_users.rb:5:in `block in up'
/Users/aa/Documents/railsy/basicProject/db/migrate/20160707230510_add_devise_to_users.rb:3:in `up'
PG::DuplicateColumn: ERROR: column "email" of relation "users" already exists
/Users/aa/Documents/railsy/basicProject/db/migrate/20160707230510_add_devise_to_users.rb:5:in `block in up'
/Users/aa/Documents/railsy/basicProject/db/migrate/20160707230510_add_devise_to_users.rb:3:in `up'
Tasks: TOP => db:migrate
(See full trace by running task with --trace)
as you can tell from my earlier user schema, there is no email column there. so ... why does this error come up?
**EDIT - should have posted devise migration file - the one that doesn't work **
class AddDeviseToUsers < ActiveRecord::Migration
def self.up
change_table :users do |t|
## Database authenticatable
t.string :email, null: false, default: ""
t.string :encrypted_password, null: false, default: ""
## Recoverable
t.string :reset_password_token
t.datetime :reset_password_sent_at
## Rememberable
t.datetime :remember_created_at
## Trackable
t.integer :sign_in_count, default: 0, null: false
t.datetime :current_sign_in_at
t.datetime :last_sign_in_at
t.inet :current_sign_in_ip
t.inet :last_sign_in_ip
## Confirmable
# t.string :confirmation_token
# t.datetime :confirmed_at
# t.datetime :confirmation_sent_at
# t.string :unconfirmed_email # Only if using reconfirmable
## Lockable
# t.integer :failed_attempts, default: 0, null: false # Only if lock strategy is :failed_attempts
# t.string :unlock_token # Only if unlock strategy is :email or :both
# t.datetime :locked_at
# Uncomment below if timestamps were not included in your original model.
# t.timestamps null: false
end
add_index :users, :email, unique: true
add_index :users, :reset_password_token, unique: true
# add_index :users, :confirmation_token, unique: true
# add_index :users, :unlock_token, unique: true
end
def self.down
# By default, we don't want to make any assumption about how to roll back a migration when your
# model already existed. Please edit below which fields you would like to remove in this migration.
raise ActiveRecord::IrreversibleMigration
end
end
EDIT AGAIN
when i run rails g devise user ... this is what comes up:
Running via Spring preloader in process 72318
invoke active_record
create db/migrate/20160707230510_add_devise_to_users.rb
insert app/models/user.rb
route devise_for :users

Turns out all I had to do was to do rake db:setup which recreates the db. Then I ran rake db:migrate, and no issues came up this time.
FYI. Hope this helps someone out there.

To eliminate migration errors on duplicate fields, use t.change as shown below.
t.change :email, :string, :null => false, :default => ""
Notice that for t.change to work, you have to specify the type for the field being changed. In the case of the email migration above, the email field was of type string.
You can refer at: devise wiki

Related

Rake db:migrate duplicate with Devise

So i'm having some issues with migrations in rails.. i have 2 migrations one to add the users table and one to add devise to users...
now im getting this error when i try run
rake db:migrate
ActiveRecord::StatementInvalid: SQLite3::SQLException: duplicate column name: email: ALTER TABLE "users" ADD "email" varchar DEFAULT '' NOT NULL
which tells me that both migrations are trying to add the column email to the users table..
USER TABLE CREATE MIGRATION
class CreateUsers < ActiveRecord::Migration
def change
create_table :users do |t|
t.string :name
t.string :email
t.string :password_digest
t.timestamps null: false
end
end
end
DEVISE ADDED TO USERS MIGRATION
class AddDeviseToUsers < ActiveRecord::Migration
def self.up
change_table(:users) do |t|
## Database authenticatable
t.string :email, null: false, default: ""
t.string :encrypted_password, null: false, default: ""
## Recoverable
t.string :reset_password_token
t.datetime :reset_password_sent_at
## Rememberable
t.datetime :remember_created_at
## Trackable
t.integer :sign_in_count, default: 0, null: false
t.datetime :current_sign_in_at
t.datetime :last_sign_in_at
t.string :current_sign_in_ip
t.string :last_sign_in_ip
## Confirmable
# t.string :confirmation_token
# t.datetime :confirmed_at
# t.datetime :confirmation_sent_at
# t.string :unconfirmed_email # Only if using reconfirmable
## Lockable
# t.integer :failed_attempts, default: 0, null: false # Only if lock strategy is :failed_attempts
# t.string :unlock_token # Only if unlock strategy is :email or :both
# t.datetime :locked_at
# Uncomment below if timestamps were not included in your original model.
# t.timestamps null: false
end
add_index :users, :email, unique: true
add_index :users, :reset_password_token, unique: true
# add_index :users, :confirmation_token, unique: true
# add_index :users, :unlock_token, unique: true
end
def self.down
# By default, we don't want to make any assumption about how to roll back a migration when your
# model already existed. Please edit below which fields you would like to remove in this migration.
raise ActiveRecord::IrreversibleMigration
end
end
im assuming its the
add_index :users, :email, unique: true
line in the 2nd migration causing this issue... but im just curious... is that line even relevant to devise? i can't find anything relating to this in the documentation... so if I were to delete those 2 lines would that have any effect on the way Devise runs??
You are trying to create column email twice: in your own migration and in devise. Also, you don't need password_digest column. Second time you got an error because the column already exists.
My advice is to rollback on version before creating users (rake db:rollback VERSION=timestamp_from_migration_filename), remove email and password_digest from your CreateUsers and try again all migrations.
change_column helper is for making multiple alteration on a single table. It always try to add column.
Please check the details on api-dock

update_attribute error when making user admin

I ran rake db:loadschema by accident last night when i was trying to edit some of my migrations to push the app up on heroku.
The admin user was working perfectly for 'admin#gmail.com'
now when i rake db:migrate my migrations again i get an error
== 20150404180803 UpdateUsers: migrating ======================================
rake aborted!
StandardError: An error has occurred, this and all later migrations canceled:
undefined method `update_attributes' for nil:NilClass/home/ubuntu/workspace/hrApp/db/migrate/20150404180803_update_users.rb:7:in `change'
/usr/local/rvm/gems/ruby-2.1.5#rails4/gems/activerecord-4.2.0/lib/active_record/migration.rb:606:in `exec_migration'
/usr/local/rvm/gems/ruby-2.1.5#rails4/gems/activerecord-4.2.0/lib/active_record/migration.rb:590:in `block (2 levels) in migrate'
class AddAdminToUsers < ActiveRecord::Migration
def change
add_column :users, :admin, :boolean, :default => false
end
end
class UpdateUsers < ActiveRecord::Migration
def change
#u = User.find_by( email: 'admin#gmail.com')
#u.update_attribute :admin , true
##u.update_attributes(:admin ,true)
end
end
class DeviseCreateUsers < ActiveRecord::Migration
def change
create_table(:users) do |t|
## Database authenticatable
t.string :email, null: false, default: ""
t.string :encrypted_password, null: false, default: ""
## Recoverable
t.string :reset_password_token
t.datetime :reset_password_sent_at
## Rememberable
t.datetime :remember_created_at
## Trackable
t.integer :sign_in_count, default: 0, null: false
t.datetime :current_sign_in_at
t.datetime :last_sign_in_at
t.string :current_sign_in_ip
t.string :last_sign_in_ip
## Confirmable
# t.string :confirmation_token
# t.datetime :confirmed_at
# t.datetime :confirmation_sent_at
# t.string :unconfirmed_email # Only if using reconfirmable
## Lockable
# t.integer :failed_attempts, default: 0, null: false # Only if lock strategy is :failed_attempts
# t.string :unlock_token # Only if unlock strategy is :email or :both
# t.datetime :locked_at
t.timestamps
end
add_index :users, :email, unique: true
add_index :users, :reset_password_token, unique: true
# add_index :users, :confirmation_token, unique: true
# add_index :users, :unlock_token, unique: true
end
end
Anyone any ideas on whats causing this error?
Thanks infused. Ive tried putting into the user model
#u = User.new(:email => "admin#gmail.com")
#u.save
gettin an error
rake aborted!
ActiveRecord::StatementInvalid: Could not find table 'users'
/usr/local/rvm/gems/ruby-2.1.5#rails4/gems/activerecord-4.2.0/lib/active_record/connection_adapters/sqlite3_adapter.rb:517:in `table_structure'
sorry should be
#u = User.new(email: 'admin#gmail.com')
#u.save
get the error
rake aborted!
ActiveRecord::StatementInvalid: Could not find table 'users'
/usr/local/rvm/gems/ruby-2.1.5#rails4/gems/activerecord-4.2.0/lib/active_record/connection_adapters/sqlite3_adapter.rb:517:in `table_structure'
/usr/local/rvm/gems/ruby-2.1.5#rails4/gems/activerecord-4.2.0/lib/active_record/connection_adapters/sqlite3_adapter.rb:389:in `columns'
The migration expects there to be a user in the database with an email address of 'admin#gmail.com':
#u = User.find_by( email: 'admin#gmail.com')
#u.update_attribute :admin , true
If that user does not exist, then #u will be nil and you'll get the error you're seeing. Add a record for that user to the database and then re-run the migrations.

How to add to devise model?

I create a user model via command rails generate devise Users.
I want my Users model to stay the same however I want to add more columns but I'm not sure how and I am still a bit confused at the moment. I am pretty new to Ruby on Rails. I am not sure what command I am supposed you run after these changes are made as well. I think it is rake db:migrate in order to update the database.
I want to be able to add
name - string
address - string
username - string ..
According to this example in the documentation,
class AddDetailsToProducts < ActiveRecord::Migration
def change
add_column :products, :part_number, :string
add_column :products, :price, :decimal
end
end
Inside the change method, add columns part_number (string) and price (decimal) to the products table
Would this
file: 20141011161019_devise_create_users.rb
class DeviseCreateUsers < ActiveRecord::Migration
def change
create_table(:users) do |t|
## Database authenticatable
t.string :email, null: false, default: ""
t.string :encrypted_password, null: false, default: ""
## Recoverable
t.string :reset_password_token
t.datetime :reset_password_sent_at
## Rememberable
t.datetime :remember_created_at
## Trackable
t.integer :sign_in_count, default: 0, null: false
t.datetime :current_sign_in_at
t.datetime :last_sign_in_at
t.inet :current_sign_in_ip
t.inet :last_sign_in_ip
## Confirmable
# t.string :confirmation_token
# t.datetime :confirmed_at
# t.datetime :confirmation_sent_at
# t.string :unconfirmed_email # Only if using reconfirmable
## Lockable
# t.integer :failed_attempts, default: 0, null: false # Only if lock strategy is :failed_attempts
# t.string :unlock_token # Only if unlock strategy is :email or :both
# t.datetime :locked_at
t.timestamps
end
add_index :users, :email, unique: true
add_index :users, :reset_password_token, unique: true
# add_index :users, :confirmation_token, unique: true
# add_index :users, :unlock_token, unique: true
end
end
First, run rake db:migrate. This will run the migration prepared by devise on your database.
After that, just add more fields to your model, just the same as you would if you'd never installed devise. The first step is to generate a new migration. Run this at the command line:
bin/rails generate migration AddNameAddressUsernameToUsers name:string address:string username:string
This will create a new migration file. You should then run that migration file on your database, with rake db:migrate again. After that, you should be able to refer to those new model fields in your controller and views.
While you could do it all in a single migration, it's generally better to keep your migrations small and discrete. This makes it easier to resolve issues if anything goes wrong.
Don't change the existing migration. You want to create a new migration with the command rails generate migration MigrationName, and then follow the Active Record Migrations Rails Guide, which gives lots of examples on how to add database columns.

failing migrations : PG::ProtocolViolation Rails

I just updated to rails4 and realized that my db roles and database was somehow not setup.
So I dropped the db and re-created the app_development db and the roles.
Now I am trying to run rake db:migrate and its failing with following error:
== DeviseCreateUsers: migrating ==============================================
-- create_table(:users)
-> 0.0081s
-- add_index(:users, :email, {:unique=>true})
-> 0.0031s
-- add_index(:users, :reset_password_token, {:unique=>true})
-> 0.0030s
== DeviseCreateUsers: migrated (0.0144s) =====================================
rake aborted!
An error has occurred, this and all later migrations canceled:
PG::ProtocolViolation: ERROR: bind message supplies 1 parameters, but prepared statement "a1" requires 0
: INSERT INTO "schema_migrations" ("version") VALUES ('20130815235601')
Tasks: TOP => db:migrate
I tried to run migrations for different tables manually and it gives the same for each table.
Here is a sample migration file that it is complaining about:
class DeviseCreateUsers < ActiveRecord::Migration
def change
create_table(:users) do |t|
## Database authenticatable
t.string :email, :null => false, :default => ""
t.string :encrypted_password, :null => false, :default => ""
## Recoverable
t.string :reset_password_token
t.datetime :reset_password_sent_at
## Rememberable
t.datetime :remember_created_at
## Trackable
t.integer :sign_in_count, :default => 0
t.datetime :current_sign_in_at
t.datetime :last_sign_in_at
t.string :current_sign_in_ip
t.string :last_sign_in_ip
## Confirmable
# t.string :confirmation_token
# t.datetime :confirmed_at
# t.datetime :confirmation_sent_at
# t.string :unconfirmed_email # Only if using reconfirmable
## Lockable
# t.integer :failed_attempts, :default => 0 # Only if lock strategy is :failed_attempts
# t.string :unlock_token # Only if unlock strategy is :email or :both
# t.datetime :locked_at
## Token authenticatable
# t.string :authentication_token
t.timestamps
end
add_index :users, :email, :unique => true
add_index :users, :reset_password_token, :unique => true
# add_index :users, :confirmation_token, :unique => true
# add_index :users, :unlock_token, :unique => true
# add_index :users, :authentication_token, :unique => true
end
end
I think one way is to delete the migration and re-create it.
But I am not sure of exact steps to do that.
Can anyone help me with exact steps with getting the migrations running. I dont mind dropping the db etc since the project is dev stage and there is not much prod data/schema I need to worry about
Thanks.
Rails 4.0
PG 9.3.0
Update1:
Dont see any rows in schema_mgrations:
select * from schema_migrations;
version
---------
(0 rows)
Update2:
Inserting by hand the same values works fine !
INSERT INTO "schema_migrations" ("version") VALUES ('20130815235601');
INSERT 0 1
select * from schema_migrations
version
----------------
20130815235601
(1 row)
Update 3
I ran migrations for different table manually and its failing for each table, so its not an issue with any specific migration.
I also tried to revert back to Rails 3.2.14 and am still facing the same issue.
Feeling lost here and stuck in it for 4-5 days now !!

PGError: ERROR: column "email" of relation "users" already exists

I've been developing a website on localhost and it wors fine. This morning, I've tried to push it to heroku using the command "git push heroku master" and then "heroku run rake db:migrate". When I try to do the second one, I have an error:
Connecting to database specified by DATABASE_URL
Migrating to DeviseCreateUsers (20130427200347)
Migrating to CreateAuthentications (20130427210108)
Migrating to AddTokenToAuth (20130427233400)
Migrating to AddNotificationToAuth (20130427234836)
Migrating to AddNotifToUser (20130428031013)
Migrating to AddDeviseToUsers (20130712103048)
== AddDeviseToUsers: migrating ===============================================
-- change_table(:users)
rake aborted!
An error has occurred, this and all later migrations canceled:
PGError: ERROR: column "email" of relation "users" already exists
: ALTER TABLE "users" ADD COLUMN "email" character varying(255) DEFAULT '' NOT N
sql_adapter.rb:652:in `async_exec'
I have found someone who had the same issue (heroku PGError: already exists 500 We're sorry, but something went wrong) but in my case the migration "AddDeviseToUsers" is not in the 'db/migrate' folder.
Previous migration affecting users table are :
class DeviseCreateUsers < ActiveRecord::Migration
def change
create_table(:users) do |t|
## Database authenticatable
t.string :email, :null => false, :default => ""
t.string :encrypted_password, :null => false, :default => ""
## Recoverable
t.string :reset_password_token
t.datetime :reset_password_sent_at
## Rememberable
t.datetime :remember_created_at
## Trackable
t.integer :sign_in_count, :default => 0
t.datetime :current_sign_in_at
t.datetime :last_sign_in_at
t.string :current_sign_in_ip
t.string :last_sign_in_ip
## Token authenticatable
# t.string :authentication_token
t.timestamps
end
add_index :users, :email, :unique => true
add_index :users, :reset_password_token, :unique => true
end
end
and
class AddNotifToUser < ActiveRecord::Migration
def change
add_column :users, :notif, :string
end
end
Thanks in advance !!
Edit - answering comments
when I run : heroku run rake db:migrate:status
up 20130427200347 Devise create users
up 20130427210108 Create authentications
up 20130427233400 Add token to auth
up 20130427234836 Add notification to auth
up 20130428031013 Add notif to user
down 20130712103048 Add devise to users
down 20130719091217 Create relationships
.
.
.
I found the answer at Devise migration on existing model.
What I did was to comment out this line in DeviseCreateUsers migration:
"t.string :email, :null => false, :default => """

Resources