我有一台Category模型
class Category < ActiveRecord::Base
attributes :id, :name, :order, :x, :y, :z
has_ancestry
end在我的控制器中,我可以使用以下代码来获取整个树作为JSON
Category.first.subtree.arrange_serializable但这将返回所有DB属性,如created_at或id
我希望使用活动模型序列化程序在不丢失树结构的情况下对输出进行整形。
class CategorySerializer < ActiveModel::Serializer
# Children is the subtree provided by ancestry
attributes :name, :x, :children
end控制器
class CategoryController < ActionController::Base
def index
category = Category.first
render :json => category
end
end上面的代码将只显示第一个子级别,而不显示子级的子级。感谢您的任何帮助
发布于 2015-11-12 20:10:00
为了使用排列,我们需要传递一个额外的参数给序列化程序,你可以这样做:
category.subtree.arrange_serializable do |parent, children|
CategorySerializer.new(parent, scope: { children: children })
end下面是如何在序列化器中获取该参数的方法:
class CategorySerializer < ActiveModel::Serializer
attributes :id, :name, :order, :children
def children
scope.to_h[:children]
end
end您可能还想看看this test,以便更好地理解arrange_serializable是如何工作的。
发布于 2016-10-07 02:59:50
在AMS 10.x (主分支)中,我们可以这样支持外部参数:
class CategorySerializer < ActiveModel::Serializer
attributes :id, :name, :order, :children
def children
instance_options[:children]
# or instance_options[:children]&.as_json
end
end接下来,您可以简单地将子代传递给序列化程序:
category.subtree.arrange_serializable do |parent, children|
CategorySerializer.new(parent, children: children)
end或
category.subtree.arrange_serializable do |parent, children|
ActiveModelSerializers::SerializableResource(parent, children: children)
endhttps://stackoverflow.com/questions/33670243
复制相似问题