Rails Active Model Serializer - 将嵌套属性添加到第二级模型

时间:2017-06-29 15:55:31

标签: ruby-on-rails ruby-on-rails-5 activemodel active-model-serializers

我有三种型号,即发票 InvoiceDetail 产品发票包含许多InvoiceDetails InvoiceDetails属于发票和产品

我分别为所有三个模型定义了序列化程序,但是当我拿取发票时,我无法获取产品属性。<​​/ p>

发票型号:

 class Invoice < ApplicationRecord
  has_many :invoiceDetails, inverse_of: :invoice
  belongs_to :customer
  accepts_nested_attributes_for :invoiceDetails
end

InvoiceDetai模型

 class InvoiceDetail < ApplicationRecord
  belongs_to :invoice
  belongs_to :product
end

产品型号

class Product < ApplicationRecord
  belongs_to :company
  belongs_to :category
  belongs_to :user
end

串行器

    class InvoiceSerializer < ActiveModel::Serializer
  attributes :id, :total_amount, :balance_amount, :created_at
  belongs_to :customer
  has_many :invoiceDetails
end

class InvoiceDetailSerializer < ActiveModel::Serializer
  attributes :id, :quantity, :discount, :subtotal
  belongs_to :product
end

class ProductSerializer < ActiveModel::Serializer
  attributes :id, :name, :mrp, :sp, :cp, :stocks, :isPublished
  has_one :category
end

当我拿取发票时: JSON输出不包含产品属性。<​​/ strong>

[
    {
        "id": 3,
        "total_amount": 450,
        "balance_amount": 350,
        "created_at": "2017-06-27T17:02:20.000Z",
        "customer": {
            "id": 4,
            "company_id": 1,
            "name": "vivek",
            "isActive": true,
            "created_at": "2017-06-27T14:35:50.000Z",
            "updated_at": "2017-06-27T14:35:50.000Z",
            "mobile": 12345678,
            "address": "test",
            "pan_number": null,
            "tin_number": null,
            "party_name": "xyz"
        },
        "invoiceDetails": [
            {
                "id": 4,
                "quantity": 1,
                "discount": 0,
                "subtotal": 150
            },
            {
                "id": 5,
                "quantity": 1,
                "discount": 0,
                "subtotal": 300
            }
        ]
    }
]

2 个答案:

答案 0 :(得分:0)

AMS不包括关联关联 - 它只有1级深度。有办法解决这个问题:

  • 在您的控制器中使用includedocs
  • 使用this one之类的解决方法 - 我目前正在制作中成功使用

答案 1 :(得分:0)

您可以添加以下初始化程序以启用递归关联。但是,您需要确保没有循环引用。

ActiveModelSerializers.config.default_includes = '**'