如何使用活动模型序列化器允许嵌套属性?

时间:2019-05-09 00:12:04

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

我正在使用Rails中的api中的active_model_serializers,我有一个控制器方法,其中通过一些计算保存了发票及其嵌套项目,问题是在包括序列化程序之后,嵌套属性受到限制,我无法访问它们。

根据一些文档,我以这种方式获得了代码,但是它不起作用

#Controller

 def invoice_params
        params.require(:invoice).permit(:person_id, :date, sales_attributes: [:reference_id, :quantity, :price])
 end

#Model

class Invoice < ApplicationRecord
    belongs_to :person
    has_many :sales
    accepts_nested_attributes_for :sales, allow_destroy: true
end

#Serializer

class InvoiceSerializer < ActiveModel::Serializer
    attributes :id, :date, :total, :profit, :consecutive, :person_id
    has_many :sales, root: :sales_attributes
    belongs_to :person
end

我要发送的json请求是:

{
    "person_id": 4,
    "date": "2019-03-20",
    "sales": [
        {
            "reference_id":1,
            "quantity": 90000,
            "price": 240
        },
        {
            "reference_id":1,
            "quantity": 50000,
            "price": 240
        }
    ]
}

有人知道会发生什么吗?在加入序列化器gem之前,它工作正常。

谢谢!

1 个答案:

答案 0 :(得分:1)

更改

invalidateSessionCancelingTasks:

SELECT a.Customer AS Customer,
       round(100.00*sum(b.Online_Sales)/sum(a.Sales), 2) AS PctOnlineSales
FROM
 ProjectId.Dataset.Big_Data_Test_1_Sales a
JOIN ProjectId.Dataset.Big_Data_Test_1_Online_Sales b
ON a.Customer = b.Customer
--WHERE a.Customer IN ('1002')
GROUP BY 1
ORDER BY 1```

def invoice_params
        params.require(:invoice).permit(:person_id, :date, sales_attributes: [:reference_id, :quantity, :price])
 end

def invoice_params
        params.require(:invoice).permit(:person_id, :date, sales_attributes: [:id, :reference_id, :quantity, :price])
 end