繁体   English   中英

将选项传递给 ActiveModel 序列化程序

[英]Passing options to ActiveModel serializer

从控制器使用序列化程序时,我可以像这样向它传递额外的选项

render json: user, some_option: 'foobar

然后我可以在序列化程序中引用some_option作为

serialization_options[:some_option]

但是,如果我直接调用序列化程序

MySerializer.new(user, some_option: 'foobar')

我无法获得额外的选项,因为serialization_options是一个空对象。

ActiveModel::Serializer 的 API 在 v0.9 中并没有真正保持一致,但是如果您升级到 v0.10,您可以使用instance_options方法来访问附加参数。 但是,我很想知道 v0.9 中的对象是如何解析的,尽管

对于 v0.9

您可以拨打以下电话:

MySerializer.new(user).as_json({some_option: 'foobar'})

如果您在另一个序列化程序中执行此操作,并且还需要传递范围和当前的 serialization_options,则可以执行以下操作:

class MyParentSerializer    

  has_one :user

  def user 
    MySerializer.new(object.user, { scope: scope }).as_json(serialization_options.merge({ some_option: 'foobar' }))    
  end

end

以下是如何从父序列化程序传递参数(选项)并根据这些参数在子序列化程序中显示或隐藏属性的方法。

父序列化器:

class LocationSharesSerializer < ActiveModel::Serializer
  attributes :id, :locations, :show_title, :show_address
     
  def locations
    ActiveModelSerializers::SerializableResource.new(object.locations, {
      each_serializer: PublicLocationSerializer,
      params: { 
        show_title: object.show_title
      },
    })
  end

end

子序列化器

class PublicLocationSerializer < ActiveModel::Serializer
  attributes :id, :latitude, :longitude, :title, :directions, :description, :address, :tags, :created_at, :updated_at, :photos

  def title
    object.title if @instance_options[:params][:show_title]
  end

end

暂无
暂无

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

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