【发布时间】:2023-03-08 17:17:01
【问题描述】:
这是我的模型:
class OrderItem < ApplicationRecord
belongs_to :order
belongs_to :product
end
class Order < ApplicationRecord
has_many :order_items
end
这是我的控制器:
def index
orders = Order.where(nil)
render json: {'orders': orders}, include:
['order_items'], status: :ok
end
我还想在 order_items 中包含该产品。我怎样才能获得以下 JSON:
{
"id": 2,
"order_items": [
{
"id": 1,
"product": {
"name": "abc"
},
}
]
},
【问题讨论】:
-
belongs_to :product 是否正确?一个订单有很多订单商品,而订单商品只有一个商品?
-
你能发布你的 schema.rb 吗?
-
create_table "order_items", force: :cascade do |t| t.integer "order_id" t.integer "product_id" t.index ["order_id"],名称:"index_order_items_on_order_id" t.index ["product_id"],名称:"index_order_items_on_product_id"
-
我已经能够解决这个问题,谢谢!
-
请您将标题更改为已解决...?
标签: activerecord active-model-serializers ruby-on-rails-5.2