简体   繁体   English

Rails ActiveRecord按连接表关联的数量排序

[英]Rails ActiveRecord sort by count of join table associations

I have a Resource model that can be voted on using the "Acts As Votable" gem ( Github page ). 我有一个Resource模型,可以使用“Acts As Votable”gem( Github页面 )进行投票。 The voting system works perfectly but I am trying to display pages ordered by how many votes each Resource has. 投票系统运作完美,但我试图按每个Resource有多少votes显示页面。

Currently my controller pulls Resources based on tags and aren't ordered: 目前我的控制器根据标签提取资源,并且没有订购:

@resources = Resource.where(language_id: "ruby")

If I take an individual resource and call "@resource.votes.size" it will return how many votes it has. 如果我获取一个单独的资源并调用“@ resource.votes.size”,它将返回它有多少票。 However, votes is another table so I think some sort of join needs to be done but I have not sure how to do it. 但是,投票是另一个表,所以我认为需要进行某种联接,但我不知道如何做。 What I need is a nice ordered ActiveRecord collection I can display like this? 我需要的是一个很好的有序ActiveRecord集合,我可以这样显示吗?

Book name - 19 votes 书名 - 19票

Book name - 15 votes 书名 - 15票

Book name - 9 votes 书名 - 9票

Book name - 8 votes 书名 - 8票

Try the following: 请尝试以下方法:

@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}" }

To include resources with 0 votes, use an outer join. 要包含0票的资源,请使用外部联接。 If the example below doesn't work as is you'll have to alter the joins statement to join across the correct relations. 如果下面的示例不起作用,则必须更改连接语句以跨越正确的关系进行连接。

@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+ Rails 5+

Built-in support for left outer joins was introduced in Rails 5 so you can use that to do this. Rails 5中引入了对左外连接的内置支持,因此您可以使用它来执行此操作。 This way you'll still keep the records that have 0 relationships: 这样您仍然可以保留具有0个关系的记录:

Resource
  .where(language_id: 'ruby')
  .left_joins(:votes)
  .group(:id)
  .select('resources.*', 'COUNT(votes.id) vote_count')
  .order('vote_count DESC')

You need to apply Group clause like this: 你需要像这样应用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")

Probably the fastest and most painful way to handle it is to use counter cache: Here is a railscast - http://railscasts.com/episodes/23-counter-cache-column . 处理它的最快和最痛苦的方法可能是使用计数器缓存:这是一个railscast - http://railscasts.com/episodes/23-counter-cache-column

In short - you simply add a column called <association_name>_count and add counter_cache: true to you association definition. 简而言之 - 您只需添加一个名为<association_name>_count的列,并将counter_cache: true添加到您的关联定义中。 Rails will take care of updating the <association_name>_count column so it always shows the number of associated objects. Rails将负责更新<association_name>_count列,以便它始终显示关联对象的数量。

Warning: it will not pre-populate this column on creation, you need to do this in your migration for all existing parent records. 警告:它不会在创建时预先填充此列,您需要在迁移中为所有现有父记录执行此操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM