【发布时间】:2017-10-09 16:35:07
【问题描述】:
我使用分类模型在 Projets 和类别之间建立了has_many, through: 关系。一个项目belongs_to一个客户。
class Client < ApplicationRecord
has_many :projets
end
class Category < ApplicationRecord
has_many :categorizations, dependent: :destroy
has_many :projets, through: :categorizations
end
class Categorization < ApplicationRecord
belongs_to :category
belongs_to :projet
end
class Projet < ApplicationRecord
belongs_to :client
has_many :categorizations, dependent: :destroy
has_many :categories, through: :categorizations
end
对于特定类别,我想列出所有项目,按客户分组。例如
(对于 category_id = 3)
客户 A 项目 1 项目 2
客户 B 项目 3
客户 C 项目 4
到目前为止,我可以做到这一点,但只能通过使用两个查询(其中一个非常低效(n+1 问题)。
这是代码
def listing
@projets_clients = Projet
.select("client_id")
.includes(:client)
.joins(:categorizations)
.where(categorizations: { category: @category })
.group("client_id")
@clients = []
@projets_clients.each do |p|
@clients << Client.includes(:projets).find(p.client_id)
end
end
如果有人可以提出更好的方法,我很想学习如何优化它,因为我自己还没有找到更好的方法。
谢谢。
【问题讨论】:
标签: sql ruby-on-rails activerecord rails-activerecord