【问题标题】:In Rails, how can you return model data from multiple different ActiveModelSerializers/Models at once?在 Rails 中,如何一次从多个不同的 ActiveModelSerializers/Models 中返回模型数据?
【发布时间】:2015-05-31 05:25:50
【问题描述】:

我有几个模型。我们称它们为 Widget 和 Gadget。

我的 Widget 和 Gadget 的#index 看起来像这样

def index
    widgets = Widget.all
    if widgets
        respond_with widgets, each_serializer: Api::V1::WidgetSerializer
    else
        render json: { message: [t(:not_found_widget)] }, status: :not_found
    end
end     

def index
    gadgets = Gadget.all
    if gadgets
        respond_with gadgets, each_serializer: Api::V1::GadgetSerializer
    else
        render json: { message: [t(:not_found_gadget)] }, status: :not_found
    end
end 

还有我的序列化器...

class Api::V1::WidgetSerializer < ActiveModel::Serializer
  attributes :id, :desc
end

 class Api::V1::GadgetSerializer < ActiveModel::Serializer
  attributes :id, :desc
end

但是,我需要一个能同时返回 1 中的资源的资源。我需要同时返回小部件和小工具。所以 json 看起来像......

{
    "widgets": [
        {
            "id": 1,
            "desc": "One"
        },
        {
            "id": 2,
            "desc": "Two"
        }
    ],
    "gadgets": [
        {
            "id": 1,
            "desc": "One"
        },
        {
            "id": 2,
            "desc": "Two"
        }
    ]
}

我怎样才能做到这一点。类似的东西

widgets = Widget.all
gadgets = Gadget.all
respond_with widgets, each_serializer: Api::V1::WidgetSerializer, gadgets, each_serializer: Api::V1::GadgetSerializer

但是,这显然行不通。

【问题讨论】:

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


    【解决方案1】:

    序列化器类不必匹配 AR 模型。序列化器类应该用作您想要生成的 JSON 的表示。在您的示例中,假设调用一个新的序列化程序DashboardSerializer,那么您可以将widgetsgadgets 都放在那里:

    class DashboardSerializer < ActiveModel::Serializer
      self.root = false
    
      attributes :widgets, :gadgets
    
      def widgets
        Widget.all
      end
    
      def gadgets
        Gadget.all
      end
    end
    

    【讨论】:

    • 我有类似的情况,但有一个问题是我需要基于 ID 获取数据,例如 Model.find course_id,但是如何将 id 从我的 API 传递到 Serializer
    【解决方案2】:

    我能看到这项工作的唯一方法是,如果您有一个模型,该模型包含 has_many 小部件和 has_many 小工具以及它自己的序列化程序,因为 AMS 会将正确的序列化程序应用于序列化程序中声明的关联。

    类似

    class Composite < ActiveRecord::Base
     has_many :widgets
     has_many :gadgets
    end
    
    class CompositeSerializer < ActiveModel::Serializer
      attributes :id
      has_many :widgets
      has_many :gadgets
    end
    

    【讨论】:

    • 有没有办法为我想要的所有对象手动构建一个大的 json 字符串并返回它? (最好减去时间戳)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多