使用设计向用户模型添加作用域



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

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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)

如果数据库中不存在新用户的电子邮件,那么添加新用户效果很好,所以我认为在如何将作用域添加到电子邮件验证中存在问题。我禁用了:validable design模块,并将验证添加到我的用户模型:

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

感谢

您可能需要创建一个迁移,以删除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

最新更新