[英]JSON with full hierarchy in Rails
I have an hierarchical structure in my app: 我的应用程序中有一个层次结构:
so my Model code looks like: 所以我的模型代码看起来像:
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
In a regular get of a record I usually need only one hierarchy below the desired record, that's why in the as_json
I merge only one hierarchy down (get Environment will return a collection of containers but those containers will not have Items) 在定期获取记录时,我通常只需要在所需记录下方的一个层次结构,这就是为什么在as_json
我仅向下合并一个层次结构(get Environment将返回容器的集合,但那些容器将没有Items)
My Question: 我的问题:
Now what I need is to add a method to the controller that allows full hierarchy response ie GET /environment/getFullHierarchy/3
will return: environment with id=3 with all its containers and for every container all it's Items & for every Item all it's expressions. 现在,我需要向控制器添加一个方法 ,该方法允许完整的层次结构响应,即GET /environment/getFullHierarchy/3
将返回: id = 3的环境及其所有容器,每个容器都包含它的Items和每个Item都包含它表达式。 without breaking the current as_json 而不破坏当前的as_json
I'm kinda new to Rails, wirking with Rails 4.2.6 & don't know where to start - can anyone help? 我对Rails有点陌生,对Rails 4.2.6感到困惑,而且不知道从哪里开始-有人可以帮忙吗?
Sure it goes something like this hopefully you get the idea. 当然,希望如此,您一定会明白。
EnvironmentSerializer.new(environment) to get the hierarchy json. EnvironmentSerializer.new(environment)以获取层次结构json。
lets say environments table has columns environment_attr1 , environment_attr2 可以说,环境表具有列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.