繁体   English   中英

使用 Rails 关联查找所有管理员

[英]Finding all Admins using Rails Associations

如何使用 Rails 6 活动记录关联找到所有管理员?

我有以下课程:

class Group < ApplicationRecord
  has_many :relationships, dependent: :destroy
  has_many :users, through: :relationships
end

class User < ApplicationRecord
  has_many :posts, dependent: :destroy
  has_many :relationships, dependent: :destroy
  has_many :groups, through: :relationships
end

class Relationship < ApplicationRecord
  belongs_to :user
  belongs_to :group
  validates :user_id, presence: true
  validates :group_id, presence: true
  validates :admin, inclusion: [true, false]

我想将管理员添加为组中的 has_many 关系。 这是我第一次尝试这样做:

has_many :admins, class_name: "User", through: :relationships

我将如何过滤那些与组的关系将 admin 属性设置为 true 的用户?

可以使用正常的查询语法来确定关联的范围

class Group < ApplicationRecord
  ...

  has_many :admins,
    -> { where({ relationships: { admin: true} }) },
    through: :relationships,
    source: :user
end

source是必要的,否则它将尝试通过Relationships.admins执行 has_many 。

group.admins等价于group.users.where({ relationships: { admin: true} })

您可以将您的 Group model 修改为:

class Group < ApplicationRecord
  scope :admins, -> { where(relationships: { admin: true }) }

  has_many :relationships, dependent: :destroy
  has_many :users, through: :relationships
end

从中您可以使用Group.joins(:users).admins来获取具有相关管理员的组。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM