简体   繁体   English

has_many通过:关系计数

[英]has_many , through: relationship count

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. 我希望有人可以帮我解决这个问题,现在已经设法解决了一个星期,我发现了很多例子,但是由于我是Rails的新手,我想我在某个地方一直犯错,我只是找不到一个正确的解决方案 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

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. 消息存在于不同的Blog中(例如Pink Blog,Green Blog,Maroon Blog等),而Blog则存在于主题(深色,鲜艳的颜色等)中,主题具有多个Blog,但是Blog只能属于一个主题。

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 BlogsMessages是Messages和Blogs之间的联系,我试图显示的是:一个主题内的前3个Blogs(按其中的消息量)

so eg 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 

(There are 8 Blogs altogether in Subject Dark Colors.) (共有8个主题为深色的博客。)

Could someone please help me with this, or at least point me in the right direction how to make it all work? 有人可以帮我这个问题,或者至少指出正确的方向如何使其全部正常工作吗?

Update: 更新:

in my Blogs_controller now i have: 在我的Blogs_controller中,我现在有:

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

in my blogs view: 在我的博客视图中:

    <% @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)

Also, in the view you could access to the new virtual attribute message_count : 另外,在视图中,您可以访问新的虚拟属性message_count

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM