Rails 多对多关联:每个组织强制使用唯一的电子邮件,但不强制执行属于不同组织的相同电子邮件

问题描述 投票:0回答:1

在这里,我通过会员资格在用户和组织之间创建了多对多关联,工作正常,但我想要的是,如果同一用户(即具有相同电子邮件的用户)属于不同的组织,则将其插入到用户表中.

这里的设计是检查用户中唯一的电子邮件验证,并且不允许相同的重复用户,但如果它属于不同的组织,我想保存它。

这是一种有效的方法吗?还有其他替代解决方案吗?

class User < ApplicationRecord
  has_many :memberships
  has_many :organizations, through: :memberships
end

# app/models/organization.rb
class Organization < ApplicationRecord
  has_many :memberships
  has_many :users, through: :memberships
end

# app/models/membership.rb
class OrganizationUser < ApplicationRecord
  belongs_to :user
  belongs_to :organization

end```

# app/db/migrate/20240810134227_devise_create_users.rb

```class DeviseCreateUsers < ActiveRecord::Migration[7.1]
  def change
    create_table :users do |t|
      ## Database authenticatable
      t.string :fullname
      t.string :email,              null: false, default: ""
      # t.integer :organization_id
      t.string :encrypted_password, null: false, default: ""

      ## Recoverable
      t.string   :reset_password_token
      t.datetime :reset_password_sent_at

      ## Rememberable
      t.datetime :remember_created_at

      ## Trackable
      # t.integer  :sign_in_count, default: 0, null: false
      # t.datetime :current_sign_in_at
      # t.datetime :last_sign_in_at
      # t.string   :current_sign_in_ip
      # t.string   :last_sign_in_ip

      ## Confirmable
      # t.string   :confirmation_token
      # t.datetime :confirmed_at
      # t.datetime :confirmation_sent_at
      # t.string   :unconfirmed_email # Only if using reconfirmable

      ## Lockable
      # t.integer  :failed_attempts, default: 0, null: false # Only if lock strategy is :failed_attempts
      # t.string   :unlock_token # Only if unlock strategy is :email or :both
      # t.datetime :locked_at


      t.timestamps null: false
    end

    # add_index :users, :email,                unique: true
    # add_index :users, [:email, :organization_id], unique: true
    add_index :users, :reset_password_token, unique: true
    # add_index :users, :confirmation_token,   unique: true
    # add_index :users, :unlock_token,         unique: true
  end
end```
ruby-on-rails ruby activerecord devise associations
1个回答
0
投票

您无需为此再创建一个 User 实例

重命名您的模型

应用程序/模型/membership.rb

class Membership < ApplicationRecord
  belongs_to :user
  belongs_to :organization
end

为会员添加唯一索引

class AddIndexForUser < ActiveRecord::Migration[7.0]
  disable_ddl_transaction!

  def change
    add_index :memberships, [:user_id, :organization_id], algorithm: :concurrently, unique: true
  end
end

然后为组织中的任何用户创建成员资格实例

Membership.create(user: user, organization: organization)
© www.soinside.com 2019 - 2024. All rights reserved.