I am using devise(4.2.0) in rails(4.2.6).
In my application, I use nested attributes in user and profile table. I need to validate the password only if I create the new record, the password field is not validated when I update the created records.
My user.rb file is:
class User < ActiveRecord::Base
has_one :profile
has_one :company_profile
accepts_nested_attributes_for :profile
attr_accessor :profile_updation
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
validates_presence_of :email, if: :email_required?
validates_presence_of :password, if: :password_required?
validates_confirmation_of :password, if: :password_required?
protected
def email_required?
true && profile_updation.blank?
end
def password_required?
!password.nil? || !password_confirmation.nil?
end
end
When I run my application this error occurred:
PG::UniqueViolation: ERROR: duplicate key value violates unique constraint "index_users_on_email" DETAIL: Key (email)=() already exists. : INSERT INTO "users" ("first_name", "last_name", "user_id", "created_at", "updated_at") VALUES ($1, $2, $3, $4, $5) RETURNING "id"
I searched this issue but I am not able to solve it.
User & profile table in schemafile
create_table "users", force: :cascade do |t|
t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
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"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "first_name"
t.string "last_name"
t.string "user_id"
end
add_index "users", ["email"], name: "index_users_on_email", unique: true, using: :btree
add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true, using: :btree
add_index "profiles", ["user_id"], name: "index_profiles_on_user_id", using: :btree
create_table "profiles", force: :cascade do |t|
t.string "company_name"
t.integer "country"
t.integer "state"
t.integer "business"
t.string "mobile_no"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "user_id"
t.boolean "terms_conditions"
end
Take a look at your test/fixtures/users.yml
file and comment out any blank fixtures. See example below:
#one: {}
#two: {}
I too had faced the same problem, drop the database and recreate it.
rake db:drop
rake db:create
rake db:migrate
hope it will work
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With