【问题标题】:How to apply ActiveModel::Serializer to a custom object?如何将 ActiveModel::Serializer 应用于自定义对象?
【发布时间】:2015-05-05 09:53:25
【问题描述】:

如果我指定简单的 ActiveModel 对象数组,序列化器可以工作:

format.json { render json: @childs, each_serializer: ItemSerializer }

但我需要用额外的字段来响应 JSON,例如parent_id 等。

{parent_id: 15, childs: @childs}

知道如何实现吗?

item_serializer.rb

class ItemSerializer < ActiveModel::Serializer
  attributes :id, :name, :parent_id
end

items_controller.rb

 def roots
    @childs = Item.where(parent_id: 15)
    respond_to do |format|
        # serializer below does not work...
        format.json { render json: {parent_id: 15, childs: @childs}, each_serializer: ItemSerializer }
    end
end

【问题讨论】:

    标签: ruby-on-rails json ruby-on-rails-4 activemodel active-model-serializers


    【解决方案1】:

    耶!我想通了!希望它可以帮助别人!

    respond_to do |format|
                format.json { render json:
                    { parent_id: parent_id, childs: ActiveModel::ArraySerializer.new(@childs, each_serializer: ItemSerializer) }
                }
            end
    

    【讨论】:

      猜你喜欢
      • 2016-07-21
      • 1970-01-01
      • 2014-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多