我有两个has_many
关系的模型,例如
公司.rb
class Company < ApplicationRecord
has_many :posts, dependent: :destroy
end
后.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个职位,但并非所有公司都如此。
我不知道这是否足以让你理解。
我现在能做什么。
如果你想像这样显示:
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