1

我正在尝试使用子域ala railscast #388 构建一个多租户应用程序。我正在使用设计进行身份验证,因此它添加了导致问题的不同扭曲。当我尝试使用已在不同子域(帐户)下构建的电子邮件添加新用户时遇到以下错误:

ActiveRecord::StatementInvalid in RegistrationsController#create

SQLite3::ConstraintException: constraint failed: INSERT INTO "users" ("account_id", "created_at", "current_sign_in_at", "current_sign_in_ip", "email", "encrypted_password", "last_sign_in_at", "last_sign_in_ip", "remember_created_at", "reset_password_sent_at", "reset_password_token", "sign_in_count", "updated_at") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)

如果新用户的电子邮件在数据库中的任何地方都不存在,则添加新用户效果很好,所以我假设我如何将范围添加到电子邮件验证中存在问题。我禁用了 :validatable devise 模块并将验证添加到我的用户模型中:

class User < ActiveRecord::Base

  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable


  attr_accessible :email, :password, :password_confirmation, :remember_me
  belongs_to :account


  validates_uniqueness_of :email, :scope => :account_id, :case_sensitive => false, :allow_blank => true, :if => :email_changed?
  validates_format_of :email, :with => Devise.email_regexp, :allow_blank => true, :if => :email_changed?
  validates_presence_of :password, :on=>:create
  validates_confirmation_of :password, :on=>:create
  validates_length_of :password, :within => Devise.password_length, :allow_blank => true

  default_scope { where(account_id: Account.current_id) }

end

class Account < ActiveRecord::Base
  attr_accessible :name, :subdomain
  has_many :clients, :dependent => :destroy
  has_many :users
  cattr_accessor :current_id

end

class ApplicationController < ActionController::Base
  protect_from_forgery

  around_filter :scope_current_account

private

  def current_account
    Account.find_by_subdomain! request.subdomain
  end
  helper_method :current_account

  def scope_current_account
    Account.current_id = current_account.id
    yield
  ensure
    Account.current_id = nil
  end

end

谢谢

4

1 回答 1

0

您可能必须创建一个迁移,以删除 Devise 添加的“index_users_on_email”索引上的唯一约束。也许是这样:

def up
  remove_index :users, :name => 'index_users_on_email'
  add_index :users, :email, :unique => false
end

def down
  remove_index :users, :name => 'index_users_on_email'
  add_index :users, :email, :unique => true
end
于 2013-09-06T15:08:59.350 回答