【问题标题】:Rails with JSON Api - including has_many relationships带有 JSON Api 的 Rails - 包括 has_many 关系
【发布时间】:2017-09-19 15:07:53
【问题描述】:

我有三个模型,Item and Transfer 和 Category(又名 Item Type):

class Item < ApplicationRecord
  belongs_to :category
  has_many :transfers
end

class Transfer < ApplicationRecord
  belongs_to :item
end

class Category < ApplicationRecord
  has_many :item
end

在我的控制器中,我有

render json: @item, include: %i[transfer category]
# FWIW the include doesn't seem to affect category at all...

这会产生一个 JSON Api 有效负载,其形状如下:

{
  data: {
      id,
      attributes: {
        /* the other attributes */
        transfers: [ { /* full transfer object */ } ]
      },
      relationships: {
        category: { data: { id, type: 'categories' } },
        transfers: { data: [ { /* full transfer object */ } ]
      }
    }
  },
  included: [ { type: 'category', id, attributes } ]
}

这些类别的行为符合我的预期。如何让每个 transfer 包含在 included 数组中,而不是嵌套在属性或关系中?

谢谢!

编辑:不是重复的。我没有尝试嵌套响应,只是将它们包含在 included 部分中以符合 JSON API 规范。无论如何,我想通了,很快就会有答案!

【问题讨论】:

  • 尝试使用transfers 而不是transfer
  • 感谢@Gerry,这是一个错字。固定的。虽然仍然不起作用:/

标签: ruby-on-rails include has-many json-api


【解决方案1】:

我认为,这个问题有点重复。看看这个:Nesting :json include in Rails

你需要使用as_json和嵌套include

【讨论】:

  • 我尝试了各种形式的渲染 json:@item,包括:{类别:真实,转移:{包括::id}}没有运气:/
【解决方案2】:

原来我错过了TransferSerializer!一旦我添加了一个,它就会像您期望的那样被放入included 数组中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多