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.
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.
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
As of 0.10 of active model serializer you can pass arbitrary options via the instance_options variable as seen here.
# posts_controller.rb
class PostsController < ApplicationController
def dashboard
render json: @post, user_id: 12
end
end
# post_serializer.rb
class PostSerializer < ActiveModel::Serializer
attributes :id, :title, :body
def comments_by_me
Comments.where(user_id: instance_options[:user_id], post_id: object.id)
end
end