mercredi 14 août 2019

How to return in serializer custom fields in relation to ruby ​on rails?

How do I add the unit_total, price fields of a relation (orders_products) to my return in products json?

Database

orders (id, user_id, ...)

products (id, name ..)

orders_products (product_id, order_id, unit_total, price)

order_serializer.rb

class OrderSerializer < ActiveModel::Serializer
  attributes :id, :item_total, :payment_total, :quotas, :shipment_total, :additional_tax_total, :total_discount, :ip_address, :origin
  has_one :user
  has_one :address
  has_one :shipping_method
  has_many :products, serializer: OrderProductSerializer
end

order_product_serializer.rb

class OrderProductSerializer < ActiveModel::Serializer
  attributes :id, :name, :SKU, :weight, :width, :height, :depth

end

models/order.rb

class Order < ApplicationRecord
  belongs_to :user
  belongs_to :address
  belongs_to :shipping_method
  has_and_belongs_to_many :products

  [...]

end

models/product.rb

class Product < ApplicationRecord
  belongs_to :brand, optional: true
  has_and_belongs_to_many :category
  has_and_belongs_to_many :order

  [...]
end

Return

{
    "orders": [
        {
            "id": 1500,
            [...],
            "user": {
                [...]
            },
            "address": {
                [..]
            },
            "shipping_method": {
                [...]
            },
            "products": [
                {
                    "id": 12,
                    "name": "Heavy Duty Rubber Bench",
                    "SKU": "B0002BWS1G",
                    "weight": 35.0,
                    "width": 30.0,
                    "height": 20.0,
                    "depth": 100.0
                },
                {
                    "id": 10,
                    "name": "Heavy Duty Steel Wallet",
                    "SKU": "B000KJW2JS",
                    "weight": 35.0,
                    "width": 30.0,
                    "height": 20.0,
                    "depth": 100.0
                },
                {
                    "id": 10,
                    "name": "Heavy Duty Steel Wallet",
                    "SKU": "B000KJW2JS",
                    "weight": 35.0,
                    "width": 30.0,
                    "height": 20.0,
                    "depth": 100.0
                }
            ]
        }
    ]
}

Aucun commentaire:

Enregistrer un commentaire