ruby-on-rails 获取ActiveRecord数组中每个对象关联记录

iqjalb3h  于 2022-11-26  发布在  Ruby
关注(0)|答案(1)|浏览(165)

我有一个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"
    },
]
jaxagkaj

jaxagkaj1#

我通过以下方式做到了这一点:

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

我不确定是否有更好的ActiveRecord-y方法来实现这一点,但它对我上面的用例很有效。

相关问题