简体   繁体   中英

Passing options to ActiveModel serializer

When using the serializer from the controller I can pass extra options to it like so

render json: user, some_option: 'foobar

Then I can reference some_option within the serializer as

serialization_options[:some_option]

But, if I call the serializer directly as

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

I cannot get the extra options since serialization_options is an empty object.

ActiveModel::Serializer's API has not really been consistent, in v0.9, however if you upgrade to v0.10, you could use the instance_options method to access the additional params. However, I'd be curious to learn how the objects were parsed in v0.9, though

For v0.9

You may call the following:

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

If you are doing that inside another serializer and you need to pass the scope and the current serialization_options as well, you can do this:

class MyParentSerializer    

  has_one :user

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

end

Here is how you can pass parameters (options) from the parent serializer and show or hide attributes based on these parameters in the child serializer.

Parent serializer:

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

Child serializer

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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