使用设计将范围添加到用户模型

时间:2013-08-14 15:50:42

标签: ruby-on-rails devise multi-tenant

我正在尝试使用子域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

由于

1 个答案:

答案 0 :(得分: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