How to pass parameters to ActiveModel serializer

我的未来我决定 提交于 2019-11-26 10:27:44

问题


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.


回答1:


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.




回答2:


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



回答3:


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



回答4:


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



回答5:


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



回答6:


serialization_options works well with Active Model Serialization 0.9.3.

The options passed along with render command can be accessed in the serializer using their keys -> serialization_options[:key]




回答7:


simple way is just add activities method in the event serializer and return n number of activities. That is it.

class EventSerializer < ActiveModel::Serializer

  has_many :activities

  def activities
    object.activities[0..9] # Select whatever you want
  end
end


来源:https://stackoverflow.com/questions/23347587/how-to-pass-parameters-to-activemodel-serializer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!