2017-02-11 3 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 조인 테이블을 올바르게 거쳐야 할당에 연결된 모든 사용자가 반환됩니다. ment.