Ruby on rails 序列化模型子级的JSON关联
我正在为我的API使用活动模型序列化程序。 我有一个模型(任务),它有许多子任务(总是任务模型),称为子任务。 我做这个递归有很多关联,这要感谢祖传宝石() 这一切都很好,但我有一个问题: 任务与用户有关联,但当活动模型序列化程序为主对象导出用户时,它不会显示所有子对象的用户详细信息。 这是我的序列化程序:Ruby on rails 序列化模型子级的JSON关联,ruby-on-rails,active-model-serializers,Ruby On Rails,Active Model Serializers,我正在为我的API使用活动模型序列化程序。 我有一个模型(任务),它有许多子任务(总是任务模型),称为子任务。 我做这个递归有很多关联,这要感谢祖传宝石() 这一切都很好,但我有一个问题: 任务与用户有关联,但当活动模型序列化程序为主对象导出用户时,它不会显示所有子对象的用户详细信息。 这是我的序列化程序: class TaskSerializer < ActiveModel::Serializer attributes :id, :name, :details, :user_id
class TaskSerializer < ActiveModel::Serializer
attributes :id, :name, :details, :user_id
belongs_to :user
has_many :children
end
class TaskSerializer
这是我的控制器:
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 Api::V1::TasksController
这是我的模型:
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
类任务
我也尝试在我的模型中这样做:
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
class Api::V1::TasksController
但不起作用…我有父对象的用户详细信息,但没有子对象的详细信息(他只向我显示用户id,没有显示所有用户对象)
有什么建议吗?您是否尝试过为子模型添加序列化程序,或者像这样将其作为显式属性查询
class TaskSerializer < ActiveModel::Serializer
attributes :id, :name, :details, :user_id, :children
def children
object.children
end
end
class TaskSerializer