繁体   English   中英

Rails活动模型序列化器has_many

[英]Rails Active Model Serializers has_many

我正在使用ActiveModelSerializers gem。 在我的模型中,用户可以有很多车辆

class User < ActiveRecord::Base
   has_many :vehicles
end

class Vehicle < ActiveRecord::Base
   belongs_to :user
end

我的序列化器:

class UserSerializer < ActiveModel::Serializer
  attributes :name, :vehicles
end

class VehicleSerializer < ActiveModel::Serializer
   attributes :color, :make, :model
end

车辆具有更多的属性,而不仅仅是颜色,品牌和型号。

如果我打印单个车辆@vehicle ,则仅显示序列化程序中指定的字段。 但是,如果我打印@user (在其序列化程序中包括:vehicles),则将忽略序列化程序,并打印Vehicle的所有字段。

我猜想这与user.vehicles是一个数组而不只是一个项目有关,但是有没有办法像序列化程序中描述的那样为每个项目打印用户车辆的整个数组?

问候。

AMS通过ActiveModel::Serializer::Association结构支持关联。 这意味着您可以在UserSerializer包含以下内容:

class UserSerializer < ActiveModel::Serializer
  attributes :name

  has_many :vehicles
end

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM