【发布时间】:2018-01-14 08:31:36
【问题描述】:
我有两个模型——父母和孩子,父母有_很多孩子,我有一个父母数组,想要检索所有父母的所有孩子,包括没有孩子的父母。 Parent 将渲染 as_json 并发送到 react 组件。
获取包含 current_user 产品的所有类别(包括没有与之关联的产品的类别)的最简洁方法是什么?
我想这样查看:
类别 1
- 产品1
- 产品 2
类别 2
- 产品1
- 产品 2
类别 3
- (空)
我已经尝试过了
@categories = Category.includes(:products).where(products: { user_id: current_user.id })
@categories.as_json(include: :products)
#Category that has no product is not included
型号
class Product < ApplicationRecord
belongs_to :user
belongs_to :category
end
class Category < ApplicationRecord
has_many :products
end
【问题讨论】:
-
您通过与用户产品的关联获取类别,而 category3 没有产品,这意味着它没有与当前用户关联的产品并且不会被退回。
标签: ruby-on-rails json activerecord ruby-on-rails-5