首页 > 解决方案 > 如何在 ruby​​ on rails 中为每个父母采取有限的职位

问题描述

我有两个模型的has_many关系像

公司.rb

class Company < ApplicationRecord
   has_many :posts, dependent: :destroy
end

post.rb

class Post < ApplicationRecord
   belongs_to :company
end

现在我试图得到这样的结果

Abc(公司包含 > 100 个帖子)

Xyz(公司包含 > 100 个帖子)

因此,概念是需要为每个公司而不是全部进行查询以获取仅两个子记录。

我试过这样

Post.order(id: :desc).group_by(&:company)

它已加载按公司分组的所有帖子,然后页面变慢。

如果我这样尝试

posts = Post.order(view_count: :desc).limit(20)
@posts = posts.group_by(&:company)

它需要 20 个职位,但并非针对所有公司。

我不知道这足以让你理解。

我现在能做什么。

标签: ruby-on-railsruby

解决方案


如果你想这样显示:

Company A
- Post A 
- Post B

Company B
- Post C
- Post D

首先获取公司列表:

@companies = Company.all #You can add condition to take only those companies you want to show

@companies.each do |company|
  #print company name
  company.posts.order("view_count DESC").limit(2).each do |post|
    #print post.title
  end
end

推荐阅读