我有一个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)
,但返回的是相同的内容。是否只需Map并执行单独的查询来查找帐户,然后将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"
},
]
1条答案
按热度按时间jaxagkaj1#
我通过以下方式做到了这一点:
我不确定是否有更好的ActiveRecord-y方法来实现这一点,但它对我上面的用例很有效。