ruby-on-rails - 如何在 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 个职位,但并非针对所有公司。
我不知道这足以让你理解。
我现在能做什么。
解决方案
如果你想这样显示:
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
推荐阅读
- menu - Facebook Messenger 持久菜单从 web_url 发送有效负载
- php - 如何在 PHPUnit 中运行特定文件?
- c# - 在viewmodel中使用IValueConverter或字符串属性将数字转换为字符串?
- html - 如何用容器类为盒子着色?
- python - 将 text.file 转换为字典并面临太多要解包的值(预期 2)
- javascript - 我编写了一个滚动指示器,它在 Microsoft Edge 中有效,但在 Google Chrome 中无效
- c# - 发送sql中的所有行进行打印
- python - TypeError: take(): argument 'index' (position 1) must be Tensor, not numpy.ndarray
- r - 这个 gsub 一个班轮有什么问题
- c# - 我如何在收据打印机上使用统一打印收据