如何使用:include,:except,:仅用于哈希:rails render中的方法

时间:2017-01-11 12:07:41

标签: ruby-on-rails json render rails-api

我需要渲染行程json但合并所有todos 作为嵌套在其中的单个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
                                       }
                                   }
                               }
                             }
                           }
                         } 

我希望将所有待办事项汇总在一起,以便客户不必整合所有待办事项,删除重复项并对其进行其他工作。

所以我在consolidated_todos模型

中创建了一个方法place
def considated_todos
  todos = self.todos
  todos += self.place_category.todos
  todos += self.climate.todos
  todos
end

然后将我的render方法改为以下

render json: @itinerary, include: {
                           places: {
                             only: [:id, :title],
                             include: :place_category,
                             methods: [:consolidated_todos],
                           }
                         }
  

如何添加:include (:todo_type等):only (:id,:content等):except :methods 返回的哈希值?

我需要做methods: [ consolidated_todos: { include: :todo_type } ]之类的事情。

修改

这个问题关于

  1. 如何序列化资源
  2. 如何包含嵌套资源
  3. 使用jbuilder / Active Model Serializer / RABL /类似的库来执行(1)或(2)
  4. 但具体是关于将include用于从:methods返回的哈希值或等效的简短解决方法(而不是使用as_json用于相同的

1 个答案:

答案 0 :(得分:-1)

我认为你不能,甚至可以,你可能应该创建不同的方法来选择所需的数据,然后在渲染对象时再选择它们。它将更容易阅读和维护。