【问题标题】:How to merge attributes from associated models into one nested attribute in serializer?如何将关联模型中的属性合并到序列化器中的一个嵌套属性中?
【发布时间】:2018-12-23 15:39:36
【问题描述】:

以下是渲染“@products”后的 json。如您所见,还有 2 个其他模型嵌套(vendor_products 和 vendor)。产品和供应商模型之间的关联是多对多的,“vendor_products”是连接表。我想在这里实现的是 - 我不想同时嵌套“vendor_products”和“vendors”模型,而是想在 vendor_products 模型中添加“vendor name”作为另一个属性。

{
   id: 1,
   barcode: 3045320001525,
   name: "xyz",
   size: "370 g",
   brand: "abc",
   img_url: "http://xyx"
   vendor_products: [
      {
        id: 1,
        v_item: "JAM101",
        vendor_id: 1,
        case_price: 72
      },
      {
         id: 2,
         v_item: "1001",
         vendor_id: 2,
         case_price: 65
      }
   ],
   vendors: [
      {
        name: "vendor_xyz"
      },
      {
        name: "vendor_123"
      }
   ]
},

下面是我想要的json格式:

{
   id: 1,
   barcode: 3045320001525,
   name: "xyz",
   size: "370 g",
   brand: "abc",
   img_url: "http://xyx"
   vendor_products: [
      {
        id: 1,
        v_item: "JAM101",
        vendor_id: 1,
        vendor_name: "vendor_xyz",
        case_price: 72
      },
      {
         id: 2,
         v_item: "1001",
         vendor_id: 2,
         vendor_name: "vendor_abc",
         case_price: 65
      }
   ],

这是我的序列化程序类:

class ProductSerializer < ActiveModel::Serializer
 attributes :id, :barcode, :name, :size, :brand, :img_url

 has_many :vendor_products
 has_many :vendors
end

class VendorProductSerializer < ActiveModel::Serializer
 attributes :id, :v_item, :vendor_id, :case_price
 belongs_to :product
 belongs_to :vendor
end

class VendorSerializer < ActiveModel::Serializer
 attributes :name
 has_many :products
 has_many :vendor_products
end

【问题讨论】:

    标签: ruby-on-rails serialization


    【解决方案1】:

    尝试在 vendor_products 序列化程序中添加自定义属性,

    class VendorProductSerializer < ActiveModel::Serializer
    
     attributes :id, :v_item, :vendor_id, :case_price, :vendor_name
     belongs_to :product
     belongs_to :vendor
    
     def vendor_name
       object.vendor.name #object is current vendor_product object get name from that
     end
    end
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-08
    相关资源
    最近更新 更多