【问题标题】:Serialize JSON association for children of a model为模型的子项序列化 JSON 关联
【发布时间】:2015-04-23 17:32:21
【问题描述】:

我正在为我的 API 使用 active-model-serializers。 我有一个模型(任务),它有很多子任务(总是任务模型),称为子任务。 由于祖先 gem (https://github.com/stefankroes/ancestry),我做了这个递归的 has_many 关联

它工作得很好,但我有这个问题: Task 与 User 有关联,但在 active-model-serializers 导出主对象的用户时,它不会显示所有子对象的用户详细信息。 这是我的序列化器:

class TaskSerializer < ActiveModel::Serializer
  attributes :id, :name, :details, :user_id

  belongs_to :user
  has_many :children

end

这是我的控制器:

class Api::V1::TasksController < Api::V1::BaseController
  respond_to :json

  def index
    @tasks = current_user.company.tasks
    respond_with @tasks, location: nil
  end
end

这是我的模型:

class Task < ActiveRecord::Base
  has_ancestry

  belongs_to :user
end

我也尝试在我的模型中这样做:

class Api::V1::TasksController < Api::V1::BaseController
  respond_to :json

  def index
    @tasks = current_user.company.tasks
    render json: @tasks,
           each_serializer: TaskSerializer,
           status: :ok

  end
end

但不起作用...我有父对象的用户详细信息,但没有子对象的用户详细信息(他只向我显示 user_id,没有所有用户对象)

有什么建议吗?

【问题讨论】:

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


    【解决方案1】:

    您是否尝试过为 Children 模型添加序列化程序或像这样将它们作为显式属性查询?

    class TaskSerializer < ActiveModel::Serializer
      attributes :id, :name, :details, :user_id, :children
    
      def children
         object.children
      end    
    end
    

    【讨论】:

      猜你喜欢
      • 2023-03-20
      • 2019-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-26
      • 2012-05-31
      • 1970-01-01
      • 2012-06-04
      相关资源
      最近更新 更多