1
votes

I'd like to call my serializer (using ASM 0.8 from master https://github.com/rails-api/active_model_serializers/tree/0-8-stable ) like this:

  def edit
    @loc=Location.find(params[:id])
    render json: @loc, serializer: LocationSmallSerializer, root: "data", meta: "success", meta_key: 'status', show_admin:true
  end

Where the show_admin value will be generated on the fly so that extra fields in the api for admin will only exist for admin users.

The serializer will look something like this:

class LocationSmallSerializer < ActiveModel::Serializer
  attributes :name, :show_admin, :admin_vals

  def admin_vals
    ????
    if @options[:show_admin]==true
      add these attributes
    end
  end

How would I merge attributes in 'admin_vals' with the attributes from above? Or if better solution, what would it be?

1
timpone, could you try the solution I posted. Let me know if you have any other question!K M Rakibul Islam

1 Answers

2
votes

You can use AMS include_attribute? in your serializer to conditionally include an attribute.

For example, to conditionally include admin_vals, you have to add a method in your serializer:

  def include_admin_vals?
    @options[:show_admin] == true
  end

If you have this in your serializer, then the admin_vals attribute will only be included if include_admin_vals? method returns true. Otherwise, admin_vals attribute will not be exposed.

To conditionally include multiple attributes of your serializer, you have to have include_attribute? checking for each of them.

e.g. if you want to conditionally include three attributes named admin_val_1, admin_val_2, admin_val_3 then you have to add these methods in the serializer:

  def include_admin_val_1?
    @options[:show_admin]==true
  end

  def include_admin_val_2?
    @options[:show_admin]==true
  end

  def include_admin_val_3?
    @options[:show_admin]==true
  end