Series classes Active Model, without an array root, but roots for children

I add a serial analyzer model label to the series, and it broke a bunch of things, one of our apis has a very specific format, which I need to save, unfortunately, it does not seem that I can get a legacy behavior.

#Models
class Parent < ActiveRecord::Base
  attr_accessable, :id, :name, :options
  has_many :children
end

class Child < ActiveRecord::Base
  attr_accessable, :id, :name
end

#Controller
class ParentsController < ApplicationController

  respond_to :json

  def index
    #Was
    @parents = Parent.all
    respond_with @parents, :include => [:children]

    #Is (and is not working)
    @parents = Parent.includes(:children)
    respond_with @parents, each_serializer: ::ParentsSerializer, root: false  #Not working
  end
...
end

#Serializer
class ParentSerializer < ActiveModel::Serializer
  attrs = Parent.column_names.map(&:to_sym) - [:options]
  attributes(*attrs)
  has_many :children

  def filter(keys)
    keys.delete :children unless object.association(:children).loaded?
    keys.add :options
    keys
  end
end

Desired output

[
  {
    "parent": {
      "id": 1,
      "name": "Uncle",
      "options":"Childless, LotsOfLoot",
      "children": []
    }
  },
  {
    "parent": {
      "id": 2,
      "name": "Mom",
      "options":"<3 Gossip, SoccerMom",
      "children": [
        {
          "child": {
            "id": 10,
            "name": "susy"
          }
        },
        {
          "child": {
            "id": 11,
            "name": "bobby"
          }
        }
      ]
    }
  }
]

I need json to be formatted so that it does not include the top root, but includes child roots ... I know that I can go with something like Rabl, but if there is an easy way to do this with Serializer ActiveModel, that would be better.

+4
source share
1 answer

, , , , . - children:

#Serializer
class ParentSerializer < ActiveModel::Serializer
  attrs = Parent.column_names.map(&:to_sym) - [:options]
  attributes(*attrs)
  has_many :children

  def filter(keys)
    keys.delete :children unless object.association(:children).loaded?
    keys.add :options
    keys
  end

  def children
    object.children.collect{|c| ChildSerializer.new(c, scope).as_json(root: :child)}
  end
end

ArraySerializer children, AM:: S.

0

Source: https://habr.com/ru/post/1539356/


All Articles