2017-02-11 31 views
1

我有User,AssignmentAccount模型。用户可以属于多个帐户,帐户有很多分配。作为帐户的管理员,您可以将用户分配给任务。我试图找出有多少用户被分配到一个特定的任务。另外,用户和分配有一个名为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 

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

+0

你的问题解决了吗? – jeffdill2

回答

0
SELECT count(users.id), assignments.id 
FROM assignment_relationships 
WHERE designated IS TRUE 
GROUP BY assignments.id 

你只需要一个表非常

1

我觉得也许我错过了你的问题的东西(因为我的答案是非常简单),但是为什么你就不能这样做:

@assignment.users.count 

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

相关问题