如何向 ActiveModel 序列化程序传递参数

我使用的是 有源模型序列化程序。我有一个模型事件,它有很多活动。

我想返回带有第一个 n 个活动的事件。我认为应该将 params n 传递给事件序列化程序。

52988 次浏览

传入的选项可以通过 @options散列获得。因此,如果您这样做:

respond_with @event, activity_count: 5

可以在序列化程序中使用 @options[:activity_count]

简单的方法是在事件序列化程序中添加活动方法并返回 n 个活动。

class EventSerializer < ActiveModel::Serializer


has_many :activities


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

@options散列在 0.9中被删除; 看起来等价的方法是 最近加入的-

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


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

Series _ options 与 Active Model Serialization 0.9.3一起工作得很好。

与呈现命令一起传递的选项可以在序列化程序中使用它们的键-> Seralization _ options [ : key ]进行访问

使用0.9.3,您可以像这样使用 # Series _ options..。

# 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

~> 0.10.0版本中,你需要使用 @instance_options:

# 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

有源模型序列化程序0.10开始,你可以通过 instance_options变量传递任意的选项,如 给你所示。

# 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