【问题标题】:How to use :include, :except, :only for hashes from :methods in rails render如何使用 :include, :except, :only 用于 Rails 渲染中 :methods 的哈希
【发布时间】: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 } ] 的事情。


编辑

这个问题不是关于

  1. 如何序列化资源
  2. 如何包含嵌套资源
  3. 使用 jbuilder / Active Model Serializer / RABL / 类似的库来执行 (1) 或 (2)

但专门针对从:methods 返回的哈希值使用include 或等效的简短解决方法(而不是使用as_json

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

    • where you select data that you need and then them when you render the object: 能不能加个例子更清楚点? 我没明白你的意思
    • 当你打破常规时,给那些试图帮助你的人否定最佳实践:/。您可能仍然想知道为什么没有得到更多回复。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-10
    • 2011-11-07
    • 2012-02-14
    • 1970-01-01
    • 2015-10-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多