如何允许用户在应用程序之间而不是在一个应用程序内使用电子邮件?

How do I allow user to have email between apps, but not inside one app?

我有我的 API 应用程序的下一个结构:

class App < ActiveRecord::Base
  has_many :users
end

class User < ActiveRecord::Base
  belongs_to :app
end

如何允许用户在应用之间拥有相同的唯一电子邮件地址,而不是在一个应用内?如果我写:

 class User < ActiveRecord::Base
  belongs_to :app
  validates :email, uniquiness: true
end

它在所有用户中全局验证电子邮件的唯一性,但我希望它只在用户所属的特定应用模型的用户中验证。

换句话说,我希望用户能够使用同一电子邮件注册 ID 为 1 的应用程序和 ID 为 2 的应用程序。

使用范围来约束此验证:

validates :email, uniquness: { scope: :app }

有关 validates 以及 uniquness 选项的更多信息,请参见 Rails Validation Documentation