設立的情況,你可以做幾乎任何事情的權利scopes和關係。
第一步是定義關係和範圍。我只是猜測你的關係是什麼,但即使完全不同的下面的代碼應該大致顯示它是如何工作:
class DeveloperReferral < ActiveRecord::Base
belongs_to :project
belongs_to :staff_member
scope :with_project, ->(project) {
# merging allows you to define conditions on the join
joins(:project).merge(Project.where(id: project))
}
scope :with_staff_member, ->(staff_member) {
# merging allows you to define conditions on the join
joins(:staff_member).merge(StaffMember.where(id: staff_member))
}
end
class RealEstateAgentAssignmentStatus < ActiveRecord::Base
has_many :developer_referrals
scope :with_status, ->(status) { where(status: status) }
scope :not_deleted, -> { where(deleted_at: nil) }
scope :with_project, ->(project) {
# merging allows you to define conditions on the join
joins(:developer_referrals).merge(
DeveloperReferral.with_project(project)
)
}
scope :with_staff_member, ->(staff_member) {
# merging allows you to define conditions on the join
joins(:developer_referrals).merge(
DeveloperReferral.with_staff_member(staff_member)
)
}
end
然後你使用範圍可以建立您的查詢。
project = Project.find(1)
staff_members = project.staff_members
statuses =
RealEstateAgentAssignmentStatus
.with_project(project)
.with_staff_member(staff_members)
.with_status([
'Pending Eligibility Check',
'Completed Eligibility Check',
])
.not_deleted
.order(
# we use `arel_table` so that SQL uses the namespaced column name
RealEstateAgentAssignmentStatus.arel_table(:rank),
)
然後你就可以做你的組/計數:
status_counts =
statuses
.group(
# we use `arel_table` so that SQL uses the namespaced column name
RealEstateAgentAssignmentStatus.arel_table(:assignment_status),
RealEstateAgentAssignmentStatus.arel_table(:rank),
)
.count(:id)