[英]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.