Juan Parra
Juan Parra

Reputation: 154

How Can I permit nested attributes with active model serializer?

I'm using active_model_serializers from an api in ruby on rails, and I have a controller method in which i save an invoice and its nested items with some calculations, the problem is that after include serializer, the nested attributes are restricted and I can't access to them.

I have the code in this way according to some documentation, but it doesn't works

#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

The json request that I'm sending is:

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

Some one knows what happen?, before of include the serializer gem it was working fine.

Thanks in advance!

Upvotes: 1

Views: 516

Answers (1)

Kamal Pandey
Kamal Pandey

Reputation: 1598

change

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

to

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

and

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

to

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

Upvotes: 1

Related Questions