[英]JSON with full hierarchy in Rails
我的应用程序中有一个层次结构:
所以我的模型代码看起来像:
class Environment < ActiveRecord::Base
has_many :containers, :dependent => :destroy
def as_json(options = {})
super(options.merge(include: :containers))
end
end
class Container < ActiveRecord::Base
has_many :items, :dependent => :destroy
belongs_to :environment
def as_json(options = {})
super(options.merge(include: :items))
end
end
class Item < ActiveRecord::Base
has_many :expressions, :dependent => :destroy
belongs_to :container
def as_json(options = {})
super(options.merge(include: :expressions))
end
end
class Expression < ActiveRecord::Base
belongs_to :item
def as_json(options = {})
super()
end
end
在定期获取记录时,我通常只需要在所需记录下方的一个层次结构,这就是为什么在as_json
我仅向下合并一个层次结构(get Environment将返回容器的集合,但那些容器将没有Items)
我的问题:
现在,我需要向控制器添加一个方法 ,该方法允许完整的层次结构响应,即GET /environment/getFullHierarchy/3
将返回: id = 3的环境及其所有容器,每个容器都包含它的Items和每个Item都包含它表达式。 而不破坏当前的as_json
我对Rails有点陌生,对Rails 4.2.6感到困惑,而且不知道从哪里开始-有人可以帮忙吗?
当然,希望如此,您一定会明白。
EnvironmentSerializer.new(environment)以获取层次结构json。
可以说,环境表具有列environment_attr1,environment_attr2
class EnvironmentSerializer < ActiveModel::Serializer
attributes :environment_attr1, :environment_attr2 , :containers
# This method is called if you have defined a
# attribute above which is not a direct value like for
# a rectancle serializer will have attributes length and width
# but you can add a attribute area as a symbol and define a method
# area which returns object.length * object.width
def containers
ActiveModel::ArraySerializer.new(object.containers,
each_serializer: ContainerSerializer)
end
end
class ContainerSerializer < ActiveModel::Serializer
attributes :container_attr1, :container_attr2 , :items
def items
ActiveModel::ArraySerializer.new(object.items,
each_serializer: ItemSerializer)
end
end
class ItemSerializer < ActiveModel::Serializer
...
end
class ExpressionSerializer < ActiveModel::Serializer
...
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.