【问题标题】:How to use the Devise gem in a Rails app where the "User" is split up between three models?如何在“用户”分为三个模型的 Rails 应用程序中使用 Devise gem?
【发布时间】:2014-03-29 22:24:37
【问题描述】:

假设我在 Rails 4 应用程序中有以下内容:

class Person < ActiveRecord::Base
  has_many :email_addresses, as: :emailable
  has_one :user_account
end

class EmailAddress < ActiveRecord::Base
  belongs_to :emailable, polymorphic: true
  # There is an :address column
end

class UserAccount < ActiveRecord::Base
  belongs_to :person
end

一个人可以有多个电子邮件地址。一个人也可以有一个用户帐户。 (我已将其移至它自己的模型中,因为并非所有人都会成为用户。)登录时,任何人的电子邮件地址都可以用作“用户名”。

鉴于此,我想使用 Devise gem。我看到您可以指定应用身份验证的模型。 User 被广泛使用,但我会使用 UserAccount。但是,Devise 然后期望电子邮件(用户名)字段在此模型中。

当一个人注册用户帐户时,实际上会创建三个关联记录(PersonEmailAddressUserAccount)。我不知道如何让 Devise 使用此设置。有什么想法吗?

【问题讨论】:

    标签: ruby-on-rails email devise associations


    【解决方案1】:

    一种选择是将电子邮件方法从您的UserAccount 委托给您的电子邮件模型,并覆盖设计登录过程使用的查找器def self.find_first_by_auth_conditions(warden_conditions)。我找到了一个相当不错的blog post,它深入描述了这一点,另一个stackoverflow answer 具有相同的方法。还有a section in the docs关于如何用多封电子邮件确认一个设计帐户。

    由于您的设置有点复杂,您也可以使用 EmailAddress 作为您的主要设计模型,并将密码方法委托给 UserAccount
    如果您必须使用可确认的且不仅是用户帐户来确认每个电子邮件地址,这可能会很有用。此设置不会覆盖该查找器,但您可能会遇到其他与委派密码有关的问题,这是以前从未尝试过的。

    【讨论】:

      【解决方案2】:

      如果您使用 ActiveRecord,

      首先,添加

      attr_accessor :email
      

      user_account(我认为这是处理设计表单最简单的方法)

      接下来,您需要修改设计登录程序。不过,在您的 user_account 中,覆盖设计方法这样的

        def self.find_for_database_authentication(warden_conditions)
          conditions = warden_conditions.dup
          if email = conditions.delete(:email)
            where(conditions.to_h).includes(:email_addresses).where(email_addresses: {email: email}).first
          else
            where(conditions.to_h).first
          end
        end
      

      您可能还需要定义以下代码才能使用上面的代码

      class UserAccount < ActiveRecord::Base
        belongs_to :person
        has_many :email_addresses, through: :person
      

      应该可以,我已经使用活动记录对此进行了测试,但是如果您使用的是 mongoid,则解决方案可能会有所不同。

      请注意,我已经修改了 devise 的 How To: Allow users to sign in using their username or email address 文档中的代码以获得解决方案。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-04-18
        • 1970-01-01
        • 2014-04-07
        • 1970-01-01
        • 2016-06-18
        • 1970-01-01
        • 1970-01-01
        • 2022-10-07
        相关资源
        最近更新 更多