简体   繁体   English

Ruby on Rails 5-在两个序列化器之间传递数据

[英]Ruby on Rails 5 - Passing data between two serializers

I would like to know if it is possible to send data from a serializer to another, not from a controller to a serializer. 我想知道是否可以将数据从串行器发送到另一个,而不是从控制器发送到串行器。 Here is what I am doing : 这是我在做什么:

class Serializer1 < ActiveModel::Serializer
  attributes \
    :id,
    :past_teachings

  def past_teachings
    p_teachings = Teaching.all
    p_teachings = ActiveModel::ArraySerializer.new(p_teachings,
                             each_serializer: Serializer2)
    #### I would like to send data to serializer2 from the current serializer ####
  end
end

I know it is possible to send data from a controller to a serializer. 我知道可以将数据从控制器发送到串行器。 But it is possible to send data from a serializer to another? 但是可以将数据从串行器发送到另一个吗?

Yes. 是。 Using AMS 0.10.x, you could change your example in this way: 使用AMS 0.10.x,您可以通过以下方式更改示例:

serializer_1.rb serializer_1.rb

class Serializer1 < ActiveModel::Serializer
  attributes :id, :past_teachings

  def past_teachings
    ActiveModelSerializers::SerializableResource.new(PastTeaching.all, each_serializer: TeachingSerializer)
  end
end

teaching_serializer.rb: Teaching_serializer.rb:

class TeachingSerializer < ActiveModel::Serializer
    attributes :id, :name
end

If you want to access the current object being serialized, you can refer to 'object.' 如果要访问当前要序列化的对象,则可以引用“对象”。 You can access the objects functions as object.function and its attributes as object['attribute']. 您可以将对象函数作为object.function及其属性作为object ['attribute']访问。

So, technically, you could do something like this (though in reality you would probably use AMS has_many relationship instead): 因此,从技术上讲,您可以执行以下操作(尽管实际上您可能会改用AMS has_many关系):

class Serializer1 < ActiveModel::Serializer
  attributes :id, :past_teachings

  def past_teachings
    ActiveModelSerializers::SerializableResource.new(object.past_teachings.where(...), each_serializer: TeachingSerializer)
  end
end

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

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