获取ActiveRecord数组中每个对象的关联记录



我有一个Posts的集合,其中Organization有许多帖子。一个岗位属于Account。模型如下所示:


# Post class
class Post < ApplicationRecord
belongs_to :account, foreign_key: 'account_id'
belongs_to :postable, polymorphic: true
validates :content, length: { in: 1..500 }
end
# Organization
class Organization < ApplicationRecord
has_many :posts, as: :postable
end

我可以得到一个组织的帖子(即在控制台中,我可以做Organization.first.posts,它返回一个形状,如:

[
{
"id": 101,
"accountId": 50,
"postableType": "Organization",
"postableId": 3,
"content": "Consequatur in illum vel voluptates.",
"createdAt": "2022-11-23T04:57:45.271Z",
"updatedAt": "2022-11-23T04:57:45.271Z"
},
{
"id": 102,
"accountId": 46,
"postableType": "Organization",
"postableId": 3,
"content": "Fugit totam minus et consequatur.",
"createdAt": "2022-11-23T04:57:45.274Z",
"updatedAt": "2022-11-23T04:57:45.274Z"
},
]
对于这个查询,包含Account对象并返回每个Post的最佳方法是什么?我试着做一些像:Organization.first.posts.includes(:account)Organization.first.posts.joins(:account),但只是返回了同样的事情。是否可以通过简单地映射并执行单独的查询来查找帐户,并将Account对象与Post合并?

例如,我理想地希望返回如下内容:

[
{
"id": 101,
"account": {
"id": 46,
"firstName": "Bob"
},
"postableType": "Organization",
"postableId": 3,
"content": "Consequatur in illum vel voluptates.",
"createdAt": "2022-11-23T04:57:45.271Z",
"updatedAt": "2022-11-23T04:57:45.271Z"
},
{
"id": 102,
"account": {
"id": 46,
"firstName": "Bob"
},
"postableType": "Organization",
"postableId": 3,
"content": "Fugit totam minus et consequatur.",
"createdAt": "2022-11-23T04:57:45.274Z",
"updatedAt": "2022-11-23T04:57:45.274Z"
},
]

我可以这样做:

Organization.first.posts.as_json(include: :account)

我不确定是否有更好的activerrecord -y方法,但它适用于我上面的用例。

最新更新