[英]Rails ActiveRecord sort by count of join table associations
我有一個Resource
模型,可以使用“Acts As Votable”gem( Github頁面 )進行投票。 投票系統運作完美,但我試圖按每個Resource
有多少votes
顯示頁面。
目前我的控制器根據標簽提取資源,並且沒有訂購:
@resources = Resource.where(language_id: "ruby")
如果我獲取一個單獨的資源並調用“@ resource.votes.size”,它將返回它有多少票。 但是,投票是另一個表,所以我認為需要進行某種聯接,但我不知道如何做。 我需要的是一個很好的有序ActiveRecord
集合,我可以這樣顯示嗎?
書名 - 19票
書名 - 15票
書名 - 9票
書名 - 8票
請嘗試以下方法:
@resources = Resouce.select("resources.*, COUNT(votes.id) vote_count")
.joins(:votes)
.where(language_id: "ruby")
.group("resources.id")
.order("vote_count DESC")
@resources.each { |r| puts "#{r.whatever} #{r.vote_count}" }
要包含0票的資源,請使用外部聯接。 如果下面的示例不起作用,則必須更改連接語句以跨越正確的關系進行連接。
@resources = Resource.select("resources.*, COUNT(votes.id) vote_count")
.joins("LEFT OUTER JOIN votes ON votes.votable_id = resources.id AND votes.votable_type = 'Resource'")
.where(language_id: "ruby")
.group("resources.id")
.order("vote_count DESC")
Rails 5
中引入了對左外連接的內置支持,因此您可以使用它來執行此操作。 這樣您仍然可以保留具有0個關系的記錄:
Resource
.where(language_id: 'ruby')
.left_joins(:votes)
.group(:id)
.select('resources.*', 'COUNT(votes.id) vote_count')
.order('vote_count DESC')
你需要像這樣應用Group子句 :
@resources = Resource.select('resources.*, count(votes.id) as votes_count').
joins(:votes).group(:id).order('votes_count DESC')
它將返回投票最多的資源
@resources.joins(:votes).group("resources.id").order("count(resources.id) DESC")
處理它的最快和最痛苦的方法可能是使用計數器緩存:這是一個railscast - http://railscasts.com/episodes/23-counter-cache-column 。
簡而言之 - 您只需添加一個名為<association_name>_count
的列,並將counter_cache: true
添加到您的關聯定義中。 Rails將負責更新<association_name>_count
列,以便它始終顯示關聯對象的數量。
警告:它不會在創建時預先填充此列,您需要在遷移中為所有現有父記錄執行此操作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.