FIX: allow multiple secondary emails

This commit is contained in:
Leo McArdle 2017-12-21 12:30:26 +00:00 committed by Guo Xiang Tan
parent 98478d78d7
commit c3129444ea
3 changed files with 48 additions and 1 deletions

View File

@ -11,7 +11,7 @@ class UserEmail < ActiveRecord::Base
validates :email, email: true, format: { with: EmailValidator.email_regex },
if: :validate_email?
validates :primary, uniqueness: { scope: [:user_id] }, if: :user_id
validates :primary, uniqueness: { scope: [:user_id] }, if: [:user_id, :primary]
validate :user_id_not_changed, if: :primary
validate :unique_email

View File

@ -0,0 +1,11 @@
class ChangeUserEmailsPrimaryIndex < ActiveRecord::Migration[5.1]
def up
remove_index :user_emails, [:user_id, :primary]
add_index :user_emails, [:user_id, :primary], unique: true, where: '"primary"'
end
def down
remove_index :user_emails, [:user_id, :primary]
add_index :user_emails, [:user_id, :primary], unique: true
end
end

View File

@ -0,0 +1,36 @@
require 'rails_helper'
require_dependency 'user_email'
describe UserEmail do
context "validation" do
it "allows only one primary email" do
user = Fabricate(:user_single_email)
expect {
Fabricate(:alternate_email, user: user, primary: true)
}.to raise_error(ActiveRecord::RecordInvalid)
end
it "allows multiple secondary emails" do
user = Fabricate(:user_single_email)
Fabricate(:alternate_email, user: user, primary: false)
Fabricate(:alternate_email, user: user, primary: false)
expect(user.user_emails.count).to eq 3
end
end
context "indexes" do
it "allows only one primary email" do
user = Fabricate(:user_single_email)
expect {
Fabricate.build(:alternate_email, user: user, primary: true).save(validate: false)
}.to raise_error(ActiveRecord::RecordNotUnique)
end
it "allows multiple secondary emails" do
user = Fabricate(:user_single_email)
Fabricate.build(:alternate_email, user: user, primary: false).save(validate: false)
Fabricate.build(:alternate_email, user: user, primary: false).save(validate: false)
expect(user.user_emails.count).to eq 3
end
end
end