【问题标题】:Serializing associations as an array of IDs将关联序列化为 ID 数组
【发布时间】:2013-03-17 00:21:02
【问题描述】:

我正在尝试将模型的关联序列化为关联模型的 ID (int) 数组。 我目前在 serializable_hash 中使用 :include 选项:

:include => {:associated => {:only => [:id]}

输出 json 像:

{"id":13, ...,"associated":[{"id":15,"associated":[]},{"id":14,"associated":[]}]}

不知道为什么关联的对象有一个“关联”键;但这不是很重要;我想要的是得到如下输出:

{"id":13, "associated":[15,14]}

我应该怎么做才能得到这个?

【问题讨论】:

    标签: ruby-on-rails-3 activemodel active-model-serializers


    【解决方案1】:

    如果您只需要 associated 模型 ID,您可以尝试在父模型中创建一个方法,例如:

    class ParentModel < ActiveRecord::Base
      # ...
    
      def associated_ids
        associated.pluck(:id)
      end
    end
    

    然后在serializable_hashto_json 方法中,我会这样做:

    parent_model_instance.includes(:associated).serializable_hash(methods: [:associated_ids])
    

    应该产生这个:

    { "id": 13, "associated_ids": [15,14] }
    

    【讨论】:

      【解决方案2】:

      也许你可以在你的序列化器中这样做:

       class SomeSerializer < ActiveModel::Serializer
         embed :ids
         has_many :associateds
       end
      

      【讨论】:

        猜你喜欢
        • 2013-11-07
        • 1970-01-01
        • 2014-01-19
        • 2011-09-20
        • 2012-05-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-04-06
        相关资源
        最近更新 更多