如何正确使用has_many在json中构建层次结构?

时间:2018-09-11 04:29:37

标签: ruby-on-rails json

我想将json显示为分层模型,但是我做错了...

谁能解释我做错了什么?

我有以下“序列化器”:

class ManagementSerializer < ActiveModel::Serializer
  attributes :managmentstructure_id, :users_id, :full_name, :users_id_parent, :managements

  def managements
    object.managments.map do |managment|
      ManagementSerializer.new(management, root: false)
    end
  end
end

和“控制器”:

def index
  @managments = Managment.all

  render json: @managments
end

我得到的是:

1

{
    "managmentstructure_id": 1,
    "users_id": 32,
    "full_name": "Test",
    "users_id_parent": null
    "managments": [
      {
        "managmentstructure_id": 2,
        "users_id": 43,
        "full_name": "Test2",
        "users_id_parent": 32
        "managments": [
          {
            "managmentstructure_id": 3,
            "users_id": 58,
            "full_name": "Test3",
            "users_id_parent": 43
          }
        ]
      }
    ]
},

2

{
  "managmentstructure_id": 2,
  "users_id": 43,
  "full_name": "Test2",
  "users_id_parent": 32
  "managments": [
          {
            "managmentstructure_id": 3,
            "users_id": 58,
            "full_name": "Test3",
            "users_id_parent": 43
          }
   ]
 },
{
  "managmentstructure_id": 3,
  "users_id": 58,
  "full_name": "Test3",
  "users_id_parent": 43
  "managments": []
 }

我的模特:

class Managment < ActiveRecord::Base
  self.table_name = 'PROJECT.V_L_MANAGMENTSTRUCTURES'
  self.primary_key = 'users_id'

  has_many :managments, class_name: 'Managment',
  foreign_key: "users_id_parent"
  belongs_to :managment, class_name: 'Managment'
end

还是不能借助“序列化器”来做到这一点?

1 个答案:

答案 0 :(得分:0)

从外观上看,这就是我要保留的方式。

class ManagementSerializer < ActiveModel::Serializer
  has_many :managements
  attributes :managmentstructure_id, :users_id, :full_name, :users_id_parent, managements

  def managements
    object.managments.map do |managment|
      ManagementSerializer.new(management, root: false).serializable_hash        
    end
  end
end