ErwinM / acts_as_tenant

Easy multi-tenancy for Rails in a shared database setup.
MIT License
1.53k stars 263 forks source link

ActiveRecord::RecordInvalid: Validation failed: Email has already been taken #249

Closed diegobernardes closed 3 years ago

diegobernardes commented 3 years ago

I'm having some problems with acts_as_tenant. The gem is working fine, but I can't create two users with the same email on different accounts. The restriction is not in the database because I'm able to insert using SQL.

# models
class Account < ApplicationRecord
  has_many :users
end

class User < ApplicationRecord
  devise :database_authenticatable, :recoverable, :rememberable, :validatable, :trackable
  acts_as_tenant :account
  validates_uniqueness_to_tenant :email # this line commented or not is the same thing.
end

# seed
ActiveRecord::Base.transaction do
  ActsAsTenant.with_tenant(Account.create!(subdomain: "account1")) do
    User.create!(name: "admin", email: "admin@admin.com", password: "123456")
  end

  ActsAsTenant.with_tenant(Account.create!(subdomain: "account2")) do
    User.create!(name: "admin", email: "admin@admin.com", password: "123456")
  end
end

When I try to execute rake db:setup I get this error: ActiveRecord::RecordInvalid: Validation failed: Email has already been taken. I can't create it from the rails console as well. I'm using Rails 6.1, acts_as_tenant 05.0, and Ruby 2.7.2.

excid3 commented 3 years ago

Devise will add a validation for email uniqueness without any knowledge of multitenancy. Pretty sure that's where your issue is coming from. You'll want to disable or modify their validation to be scoped to tenant.

diegobernardes commented 3 years ago

Thanks! Forgot about that. Way too much time away of rails 😅 I did forgot these little things.