如何解决在Rails中按关联状态状态进行排序
我创建了具有has_many与Response模型的关联的候选模型
在响应模型中,我们还将状态存储为待处理和已完成
我想添加一个范围,该范围根据待定状态的数量对候选人进行排序
例如
Candidates1 -> repsones1 --> {status: "pending"}
-> repsones2 --> {status: "completed"}
*******************************************************
Candidates2 -> repsones1 --> {status: "pending"}
-> repsones2 --> {status: "pending"}
*******************************************************
Candidates3 -> repsones1 --> {status: "completed"}
-> repsones2 --> {status: "completed"}
*******************************************************
Candidates4 -> repsones1 --> {status: "pending"}
-> repsones2 --> {status: "pending"}
所以从上面的例子中,我想这样订购
Candidates2 #pending status count is 2
Candidates4 #pending status count is 2
Candidates1 #pending status count is 1
Candidates3 #pending status count is 0
我正在使用Postgres作为数据库
我不想在候选模型上添加任何计数属性
我尝试了一些范围
class Candidate < ActiveRecord::Base
has_many :responses
scope :order_by_pending_responses,-> {
joins(:responses)\
.order("responses.status='pending' DESC")
}
end
但获得重复的候选人 如果我在范围上添加了uniq关键字,则会出现分页错误
解决方法
SQL中的
ORDER BY
子句可以包括聚合和条件:
scope :order_by_pending_responses,-> {
left_joins(:responses)
.group("candidates.id")
.order("SUM(CASE WHEN responses.status = 'pending' THEN 1 ELSE 0 END) DESC")
}
,
尝试一下:
scope :order_by_pending_responses,-> {
left_joins(:responses)
.where(responses: { status: :pending })
.group("candidates.id")
.order("count(responses.id) DESC")
}
但是,如果您要经常调用该范围,建议您使用内置的counter_cache:
class Response < ActiveRecord::Base
belongs_to :candidate,counter_cache: true
# ...
end
# add a migration
add_column :candidates,:responses_count,:integer,default: 0
# Candidate model
class Candidate < ActiveRecord::Base
scope :order_by_pending_responses,order('responses_count DESC')
# ...
end
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。