2016-07-28 40 views
0

加入嵌套协会,团体和秩序我有嵌套的模型结构:通过计数

class Forum < ActiveRecord::Base 
    has_many :topics 

class Topic < ActiveRecord::Base 
    has_many :posts 
    belongs_to :forum 

class Post < ActiveRecord::Base 
    belongs_to :topic 
    has_many :post_links 
    has_many :links, ->{ uniq }, through: :post_links, dependent: :destroy 

class PostLink < ActiveRecord::Base 
    belongs_to :post 
    belongs_to :link 

class Link < ActiveRecord::Base 
    has_many :post_links 
    has_many :posts, ->{ uniq }, through: :post_links, dependent: :destroy 

所以我想这是帖子说是主题,在论坛,ID = 1

所有链接

按照论坛中出现的次数降序排列。

所以,如果我有一些职位youtube.com 5次论坛,ID = 1,和10时google.com话,我想有这样的:

id,name,mentions_count 
1,google.com,10 
2,youtube.com,5 
+0

计数什么? – emrahbasman

+0

在这个论坛的所有帖子链接提及次数。 –

+0

在论坛1中订购帖子的链接数量? – emrahbasman

回答

0
Forum.where(id: 1).joins(topics: [posts: [:links]]).order("count_all DESC").group("links.host").count 
=> {"youtube.com"=>5, "google.com"=>2} 

我假设你有在你的链接表中的主机列