【问题标题】:How to find number of records based on association through join table如何通过连接表根据关联查找记录数
【发布时间】:2017-02-11 03:01:39
【问题描述】:

我有UserAssignmentAccount 模型。用户可以属于多个帐户,并且帐户有许多分配。作为帐户的管理员,您可以将用户“分配”到分配中。我试图找出有多少用户被分配给一个特定的任务。此外,用户和分配有一个名为assignment_relationships 的连接表。该表有一个布尔值,如果用户被分配到该表,则该布尔值会翻转——该属性称为designated。这有点令人困惑,但应该很简单。以下是关联:

用户:

class User < ApplicationRecord
  has_many :account_memberships
  has_many :accounts, through: :account_memberships
  has_many :assignment_relationships
  has_many :assignments, through: :assignment_relationships
end

帐号:

class Account < ApplicationRecord
  has_many :assignments
end

作业:

class Assignment < ApplicationRecord    
  belongs_to :account
  has_many :assignment_relationships
  has_many :users, through: :assignment_relationships
end

assignment_relationships:

class AssignmentRelationship < ApplicationRecord
  belongs_to :user
  belongs_to :assignment
end

因此,作为回顾,我试图找到一个查询来告诉我有多少用户被分配到一个特定的任务中。感谢您的帮助!

【问题讨论】:

    标签: mysql ruby-on-rails ruby rails-activerecord


    【解决方案1】:

    我觉得我可能在你的问题中遗漏了一些东西(因为我的答案非常简单)但是你为什么不能这样做:

    @assignment.users.count
    

    由于您的has_many, through: 关系似乎已正确设置,因此在Assignment 对象上调用users 应该正确地通过您的assignment_relationships 连接表以返回任何连接到分配的用户。

    【讨论】:

      【解决方案2】:
      SELECT count(users.id), assignments.id
      FROM assignment_relationships
      WHERE designated IS TRUE
      GROUP BY assignments.id
      

      理想情况下你只需要一张桌子

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-01-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-02-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多