【问题标题】:In Rails, how do I return an associated record using includes?在 Rails 中,如何使用包含返回关联记录?
【发布时间】:2020-12-17 22:50:57
【问题描述】:

我知道 include 和 extract_associated 方法。

在 Rails 文档中,此处使用的提取关联仅返回用户记录 -

account.memberships.extract_associated(:user)
# => Returns collection of User records 

我希望在同一个数组中返回成员资格记录和用户记录。我知道 includes 方法应该为我执行此操作,但我的响应仅包含 user_id 而不是实际记录,即包含的使用根本没有改变返回的内容,如下所示:-

account.memberships.includes(:user)
# => Returns collection of Membership records, with user_ids 
[{ "id": 3, "account_id": 1, "user_id": 2, "membership_name": 'Annual Membership'}]

我的会员资格属于_一个用户,而一个用户拥有_许多会员资格。

我在这里错过了什么?

在我看来,membership.user 不是我的选择,因为我使用的是 VueJS,所以需要传递我需要的所有数据。

【问题讨论】:

  • 使用对象是最好的/红宝石方式。也就是说,尝试同时使用“joins”和“includes”,看看是否能满足您的需求。希望你能从中得到你需要的东西,否则你还需要指定一个“选择”。

标签: ruby-on-rails ruby activerecord


【解决方案1】:

您可以将关联的集合包含为 json。

account.memberships.includes(:user)
       .as_json(include: { memberships: { include: :user } })

从文档中查看 API 的详细信息。 https://api.rubyonrails.org/classes/ActiveModel/Serializers/JSON.html

【讨论】:

    猜你喜欢
    • 2012-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多