Rails嵌套的序列化程序不使用方法来分解键

时间:2017-09-22 20:17:32

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

我想在另一个序列化程序中使用序列化程序,因此我可以在顶层添加一个键值对,但就像我一样,较低级别的序列化程序不再起作用了 -

我的档案:

上述ItemsController

class ItemsController

  def index
    open_items = Items.
      select("distinct on (open_item_id) *").
      preload(:company, :project)

    total = open_items.count("id")

    render json: {
      total: total,
      items: paginate(open_items, per_page: 2), serializer: ItemsSerializer
    }, status: :ok
  end
end

ItemsSerializer

class ItemsSerializer < ActiveModel::Serializer
  attribute :total
  has_many :items, serializer: ItemSerializer
end

ItemSerializer

class ItemSerializer&lt; ::加载ActiveModel串行       属性:id,         :项目,         :公司,

  def company
    {
      name: object.company.name,
      id: object.company.id
    }
  end

  def project
    {
      name: object.project.name,
      id: object.project.id
    }
  end

end

我想在下面的序列化器输出中获得另一个键/值对,以便我可以得到这样的结果:

{
    "total": 1,
    "items": [
        {
          "id": 42920375,
          "company": {
            "id": 123,
            "name": "CompanyName"
          },
          "project": {
            "id": 456,
            "name": "ProjectName"
          }
        }
    ]
}

但是目前,我得到了:

{
    "total": 1,
    "items": [
        {
            "id": 42920375,
            "company_id": 5842,
            "project_id": 191741,
        }
    ]
}

1 个答案:

答案 0 :(得分:0)

我不认为你可以这样使用ItemsSerializer。它需要与模型相对应。

Active-Model-serializer将自动序列化与自己的序列化程序关联的每个对象:

"In your controllers, when you use render :json for an array of objects, AMS will use ActiveModel::ArraySerializer (included in this project) as the base serializer, and the individual Serializer for the objects contained in that array."

所以没有必要重新发明轮子。就这样做:

final_some_list = [app for app in some_list for other_app in other_list 
if not app[1] == other_app[1] and app[2] == other_app[2] and app[3] == 
other_app[3]

final_some_list = [app for app in some_list for other_app in other_list 
if not app[1] and app[2] and app[3] == in other_app

然后,render json: paginate(open_items, per_page: 2), status: :ok 将处理每个项目。我没有看到在这里添加ItemSerializer的方法。