How to pass parameters to ActiveModel serializer

I'm using active model serializer. I have a model event which has_many activities.

I want to return the event with the first n activities. I think I should pass the params n to the event serializer.


In version ~> 0.10.0 you need to use @instance_options. Using @Jon Gold example from above:

# controller
def action
  render json: @model, option_name: value
end

# serializer
class ModelSerializer::ActiveModel::Serializer
  def some_method
    puts @instance_options[:option_name]
  end
end

Options passed in are available through the @options hash. So if you do:

respond_with @event, activity_count: 5

You can use @options[:activity_count] within the serializer.


The @options hash was removed in 0.9; looks like an equivalent method was recently added -

def action
  render json: @model, option_name: value
end

class ModelSerializer::ActiveModel::Serializer
  def some_method
    puts serialization_options[:option_name]
  end
end

Using 0.9.3 you can use #serialization_options like so...

# app/serializers/paginated_form_serializer.rb
class PaginatedFormSerializer < ActiveModel::Serializer
  attributes :rows, :total_count

  def rows
    object.map { |o| FormSerializer.new(o) }
  end

  def total_count
    serialization_options[:total_count]
  end
end

# app/controllers/api/forms_controller.rb
class Api::FormsController < Api::ApiController
  def index
    forms = Form.page(params[:page_index]).per(params[:page_size])
    render json: forms, serializer: PaginatedFormSerializer, total_count: Form.count, status: :ok
  end
end