简体   繁体   English

active_model_serializers关联为:

[英]active_model_serializers association as:

I'm using ActiveModel::Serializer in my rails-api app. 我在rails-api应用程序中使用ActiveModel :: Serializer。 I have a polymorphic association called addonable: 我有一个称为addonable的多态关联:

class AddOn < ActiveRecord::Base
  belongs_to :addonable, polymorphic: true
end
class Container < ActiveRecord::Base
  has_many :add_ons, as: :addonable
end
class Depot < ActiveRecord::Base
  has_many :add_ons, as: :addonable
end

Then, I have two different controllers, each of them returns a different addonable (Container or Depot). 然后,我有两个不同的控制器,每个控制器返回一个不同的addonable(容器或仓库)。 I would like the serializer to return the addonable association with its class name: 我希望序列化程序返回带有其类名的addonable关联:

class DepotSelectSerializer < ActiveModel::Serializer
  attributes :id, :quantity

  belongs_to :addonable,  serializer: DepotSerializer, polymorphic: true
end
#returns: {:data=>{:id=>:string, :type=>:string, :attributes=>{:quantity=>:integer}, :relationships=>{:addonable=>{:data=>:object}}}}

#I want: {:data=>{:id=>:string, :type=>:string, :attributes=>{:quantity=>:integer}, :relationships=>{:depot=>{:data=>:object}}}}

I want the object to be in the relationships hash, not in the attributes, that's why I cannot use a custom method. 我希望对象位于关系哈希中,而不是属性中,这就是为什么我不能使用自定义方法的原因。

Ideally, I would have something like: 理想情况下,我将具有以下内容:

belongs_to :addonable,  serializer: ContainerSerializer, polymorphic: true, as: :depot

But I cannot find anything similar. 但是我找不到类似的东西。 Is this possible? 这可能吗? Thanks in advance 提前致谢

From active_model_serializer document , it describes: active_model_serializer 文档中 ,它描述了:

You may also use the :serializer option to specify a custom serializer class and the :polymorphic option to specify an association that is polymorphic (STI), eg: 您也可以使用:serializer选项指定自定义序列化器类,并使用:polymorphic选项指定多态(STI)关联,例如:

has_many :comments, :serializer => CommentShortSerializer has_many:comments,:serializer => CommentShortSerializer

has_one :reviewer, :polymorphic => true has_one:reviewer,:polymorphic => true

Serializers are only concerned with multiplicity, and not ownership . 序列化程序仅关注多重性,而不关注所有权 belongs_to ActiveRecord associations can be included using has_one in your serializer. 可以在序列化器中使用has_one来包括属ActiveRecord关联。

So in your case, let use has_one instead of belongs_to : 因此,在您的情况下,请使用has_one而不是belongs_to

has_one :addonable, serializer: DepotSerializer, polymorphic: true

Tested, it works in my project! 经过测试,可以在我的项目中使用!

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

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