如何将参数传递给ActiveModel序列化器


Answers:


47

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

respond_with @event, activity_count: 5

您可以@options[:activity_count]在序列化器中使用。


7
从AMS 0.9.0开始,此功能无效。由于AMS没有文档,没有Wiki,也没有讨论区,因此这似乎是一个死胡同。
— 罗宾·多尔蒂

1
这似乎不起作用。该文件在哪里?
— 大卫


2
如果可以的话,更安全地使用0.8版本,因为AMS团队建议使用它。 we recommend that any new projects you start use the latest 0.8.x version of this gem. This version is the most widely used, and will most closely resemble the forthcoming release.
— bigtex777

21
@options似乎不适用于我,事实证明哈希改为 @instance_options。对我来说就做到了。
— the_critic

110

在版本中,~> 0.10.0您需要使用@instance_options。使用上面的@Jon Gold示例:

# 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.10上执行此操作
— moondaisy

42

的@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

4
我有gem版本0.9(只是为了确保对其进行了更新),但是options和serialization_options都不起作用。这是错误的未定义局部变量或方法“ serialization_options”
— ganeshran 2014年

1
ganeshran是正确的。serialization_options应该适用于0.9,但似乎使用0.8,@options是目前唯一可行的方法。
— jmosesman 2014年

12

使用0.9.3,您可以像这样使用#serialization_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

9

作为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

8

serialization_options与Active Model Serialization 0.9.3兼容。

可以在序列化器中使用其键-> serialization_options [:key]访问与render命令一起传递的选项。


-2

简单的方法是在事件序列化器中添加活动方法并返回n个活动。这就对了。

class EventSerializer < ActiveModel::Serializer

  has_many :activities

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

1
除非您对返回的活动进行了硬编码。“选项”哈希的全部要点是让API向端点的使用者提供不同的选项。
— rmcsharry16年
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.