【发布时间】:2017-01-11 12:07:41
【问题描述】:
我需要渲染行程json,但将所有待办事项合并作为嵌套在其中的单个json数组:
render json: @itinerary, include: {
places: {
only: [:id, :title],
include: {
todos: {
only: [:id, :content],
include: :todo_type
},
place_category: {
include: {
todos: {
only: [:id, :content],
include: :todo_type
}
}
},
climate: {
include: {
todos: {
only: [:id, :content],
include: :todo_type
}
}
}
}
}
}
我希望将所有待办事项一起渲染,这样客户端就不必整合所有待办事项、删除重复项和对其进行其他工作。
所以我在place模型中创建了一个方法consolidated_todos
def considated_todos
todos = self.todos
todos += self.place_category.todos
todos += self.climate.todos
todos
end
然后把我的渲染方法改成如下
render json: @itinerary, include: {
places: {
only: [:id, :title],
include: :place_category,
methods: [:consolidated_todos],
}
}
如何添加
:include(:todo_type, etc.,),:only(:id, :content, etc.,) 和@987654328 @对于从:methods返回的哈希值?
我需要做类似methods: [ consolidated_todos: { include: :todo_type } ] 的事情。
编辑:
这个问题不是关于
- 如何序列化资源
- 如何包含嵌套资源
- 使用 jbuilder / Active Model Serializer / RABL / 类似的库来执行 (1) 或 (2)
但专门针对从:methods 返回的哈希值使用include 或等效的简短解决方法(而不是使用as_json)
【问题讨论】:
标签: ruby-on-rails json render rails-api