简体   繁体   English

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

[英]Finding all Admins using Rails Associations

How do I find all admins using Rails 6 active record associations?如何使用 Rails 6 活动记录关联找到所有管理员?

I have the following classes:我有以下课程:

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]

I'd like to add admins as a has_many relationship in Group.我想将管理员添加为组中的 has_many 关系。 Here's my first attempt at doing so:这是我第一次尝试这样做:

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

How would I filter those users whose relationship to the group has the admin attribute set to true?我将如何过滤那些与组的关系将 admin 属性设置为 true 的用户?

Associations can be scoped using the normal query syntax.可以使用正常的查询语法来确定关联的范围

class Group < ApplicationRecord
  ...

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

source is necessary because otherwise it will try to do the has_many through Relationships.admins . source是必要的,否则它将尝试通过Relationships.admins执行 has_many 。

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

You could've modified your Group model to something like:您可以将您的 Group model 修改为:

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

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

From it you can use Group.joins(:users).admins to get groups with assoiciated admins.从中您可以使用Group.joins(:users).admins来获取具有相关管理员的组。

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

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