Rails 3的顺序按指望的has_many:通过顺序、Rails、has_many

由网友(自罚三杯)分享简介:我有一个应用程序,我可以列表项,并添加标签到每个项目。这些模型项和标签相关联是这样的:类项目<的ActiveRecord :: Base的的has_many:的Tagging的has_many:标签,:通过=> :的Tagging结束类标记<的ActiveRecord :: Base的belong...

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

类项目<的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降序)
 

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

Railsosdc 专业指导文档类资源 CSDN下载

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

顺便说一句,你为什么不尝试了这一点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

阅读全文

相关推荐

最新文章