Rails 3 Order By Count on has_many :through [英] Rails 3 Order By Count on has_many :through

查看:21
本文介绍了Rails 3 Order By Count on has_many :through的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个应用程序,我可以在其中列出项目并为每个项目添加标签.模型 ItemsTags 的关联如下:

I have an application where I can list Items and add tags to each Item. The models Items and Tags are associated like this:

class Item < ActiveRecord::Base
  has_many :taggings
  has_many :tags, :through => :taggings
end

class Tagging < ActiveRecord::Base
  belongs_to :item
  belongs_to :tag
end

class Tag < ActiveRecord::Base
  has_many :taggings
  has_many :items, :through => :taggings
end

所以,这种多对多的关系让我可以为每个Item设置n个标签,并且同一个标签可以多次使用.

So, this many-to-many relationship allows me to set n tags for each Item, and the same tag can be used several times.

我想列出按与此标签关联的项目数排序的所有标签.使用较多的标签,先展示.少用,最后.

I'd like to list all tags ordered by the number of items associated with this tag. More used tags, shows first. Less used, last.

我该怎么做?

问候.

推荐答案

Tag.joins(:taggings).select('tags.*, count(tag_id) as "tag_count"').group(:tag_id).order(' tag_count desc')

尝试 desc 和 asc 看看有什么不同.

try it desc, asc and see the difference.

我们需要select,有tag_count 列,我们需要tag_count 列来应用order 到它,其余的直接join分组.

We need select, to have tag_count column, and we need tag_count column to apply order to it, rest all straight forward join and grouping.

顺便说一句,你为什么不试试这个https://github.com/mbleigh/acts-as-taggable-开

Btw, why dont you try this out https://github.com/mbleigh/acts-as-taggable-on

这篇关于Rails 3 Order By Count on has_many :through的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆