has_many,through:关系计数 [英] has_many , through: relationship count

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

问题描述

我希望有人能帮助我,一直试图找出一个星期,我发现了很多例子,但因为我是新的rails我想我在某个地方不断犯错,我只是找不到一个正确的解决方案,我的情况。
所以我有:

I was hoping someone could help me with this, been trying to figure it out for a week now, I found a lot of examples, but as I'm new to rails I guess I keep making a mistake somewhere and I just cant find a right solution for my case. So I have:

class Blog < ActiveRecord::Base
   attr_accessible :name, :subject_id, :created_at
   has_many :blogs_messages
   has_many :messages, through: :blogs_messages
end

class Message < ActiveRecord::Base
   attr_accessible :title, :body, :created_at
   has_many :blogs_messages
   has_many :blogs, through: :blogs_messages
end

class BlogsMessages < ActiveRecord::Base
  attr_accessible :message_id, :blog_id
  belongs_to :blog
  belongs_to :message
end

消息存在于不同的博客(如粉红色博客,绿色博客,Maroon博客等)和博客生活在主题(深色,亮色等)
主题有很多博客,但博客只能属于一个主题。

Messages live in different Blogs(like Pink Blog, Green Blog, Maroon Blog etc), and Blogs live in Subjects (Dark Colors, Bright Colors etc) Subjects have many Blogs, but Blogs can belong only to one Subject.

博客消息是消息和博客之间的连接
我想要做的是显示:
top 3博客(按其中的邮件数量)一个主题

BlogsMessages is the connection between Messages and Blogs what im trying to do is to show: top 3 Blogs (by amount of messages in them) within one Subject

当我想选择主题暗色它会显示我:

so e.g. when I want to choose Subject Dark Colors it will show me:

    1.Maroon Blog: 46 messages
    2.Grey Blog: 13 messages
    3.Purple Blog: 12 messages 

有人可以帮我解决这个问题,或至少告诉我正确的方向如何使它一切正常?

Could someone please help me with this, or at least point me in the right direction how to make it all work?

更新:

在我的Blogs_controller中现在有:

in my Blogs_controller now i have:

@blogs = Blog.joins(:blogs_messages => :message).select('blogs.*, COUNT(messages.id) AS message_count').group('blog_id').order('COUNT(messages.id) DESC').limit(3)

在我的博客视图中:

    <% @blogs.each do |blog| %>
      <li><%= blog.name %>:  messages</li>
    <% end %>


推荐答案

我不确定这可以工作,因为我可以不测试它,但它可能会帮助你:

I'm not sure this can work because I can't test it but it may help you:

 Blog.where(subject_id: subject.id)
      .joins(:blogs_messages => :message)
      .select('blogs.*, COUNT(messages.id) AS message_count')
      .group(:blog_id)
      .order('message_count DESC')
      .limit(3)

此外,新的虚拟属性 message_count

 <% @blogs.each do |blog| %>
   <li><%= blog.name %>: <%= blog.message_count %> messages</li>
 <% end %>

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

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