【问题标题】:Get a belongs_to relationship from class Ruby on Rails从 Ruby on Rails 类中获取 belongs_to 关系
【发布时间】: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


【解决方案1】:

你可以通过改变来达到这个目的 include: ['order_items']include: ['order_items', 'order_items.product'].

更多详情您可以获取here

【讨论】:

  • 我试过了,它给了我 NoMethodError: undefined method
【解决方案2】:

我已经能够通过将include: ['order_items'] 更改为include: {'order_items': {include: 'product'}} 来解决这个问题

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多