Rails 3的顺序按指望的has_many:通过 [英] Rails 3 Order By Count on has_many :through

查看:182
本文介绍了Rails 3的顺序按指望的has_many:通过的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个应用程序,我可以列表项,并添加标签到每个项目。 这些模型标签相关联是这样的:

类项目<的ActiveRecord :: Base的   的has_many:的Tagging   的has_many:标签,:通过=> :的Tagging 结束 类标记<的ActiveRecord :: Base的   belongs_to的:项目   belongs_to的是:标签 结束 类标签<的ActiveRecord :: Base的   的has_many:的Tagging   的has_many:项目:通过=> :的Tagging 结束

那么,这么多的一对多的关系,可以让我将 N 标记的每个项目,和相同的标记可以多次使用。

我想列出下令由与此标记关联的项目数的所有变量。更多使用标签,显示第一。少用,最后。

我怎么能这样做?

问候。

解决方案

  Tag.joins(:的Tagging)。选择('标签*,COUNT(tag_id)为tag_count' )。集团(:tag_id).order('tag_count降序)
 

尝试递减,递增,看到了差距。

我们需要的选择的,有tag_count列,我们需要tag_count列申请的的给它,其余全部直截了当的加入的和分组的。

顺便说一句,你为什么不尝试了这一点<一个href="https://github.com/mbleigh/acts-as-taggable-on">https://github.com/mbleigh/acts-as-taggable-on

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

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.

How can I do that?

Regards.

解决方案

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

try it desc, asc and see the difference.

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.

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

这篇关于Rails 3的顺序按指望的has_many:通过的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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