我正在开发一个现有的应用程序,它的结构(简化和)如下所述。我们的一个新查询是查找一家公司中的所有活动,该公司相当复杂且构建时表现不佳。在 ActiveRecord 中编写查询似乎很困难,因此,我正在尝试使用 Scenic 并构建一个物化视图,因为此查询将主要是只读的。
所以,我们有Person
, Group
, Project
, Report
,Update
和ActivityReceipt
一些连接模型。一个人属于不同的群体和不同的项目。
我的目标是显示成员所属的所有组的组活动的提要,因此我希望Activity
通过group
以及author
按时间排序的信息来高效地获取,它似乎是一个具有以下内容的物化视图列会实现这一点:
activity_receipt_id, group_id, person_id
class Person < ApplicationRecord
has_many :groups
has_many :projects
end
class Membership < ApplicationRecord
# id, group_id, person_id
belongs_to :group
belongs_to :person
end
class Company < ApplicationRecord
has_many :projects
has_many :people
end
class GroupDonation < ApplicationRecord
# id, group_id, project_id
belongs_to :group
belongs_to :project_id
end
class Project < ApplicationRecord
has_many :group_donations
has_many :people
end
class ActivityReceipt < ApplicationRecord
# polymorphic belongs_to relation to 'postable' which are reports, & updates
# so, it has id, postable_id, and postable_type as columns and then other specific metadata
belongs_to :postable
end
class Report < ApplicationRecord
# project_id, membership_id and other specific metadata
belongs_to :project
belongs_to :membership #to track the author
has_one :activity_receipt
end
class Update < ApplicationRecord
# project_id, membership_id and other specific metadata
belongs_to :project
belongs_to :membership #to track the author
has_one :activity_receipt
end
从概念上讲,查询是针对所有给定的group_ids
,获取相关的项目,然后是它们的相关报告和更新,然后是最终需要的活动收据。我不太熟悉编写 SQL 来生成视图,所以我一直在努力研究如何使用多态关系制作这样的物化视图,如果它甚至可能/推荐
这是我到目前为止所拥有的:
SELECT groups.id AS group_id, people.id AS people_id, activity_receipts.id as activity_receipt_id
FROM groups
JOIN group_donations ON group_donations.group_id = groups.id
JOIN projects ON projects.id = group_donations.group_id
JOIN reports ON reports.project_id = project.id
JOIN updates ON updates.project_id = project.id
JOIN activity_receipts ON
// Stuck here