【问题标题】:How to render nested resources as json in rails if each nested resource could also have resource nested under it?如果每个嵌套资源也可以在其下嵌套资源,如何在 Rails 中将嵌套资源呈现为 json?
【发布时间】:2016-11-06 18:39:55
【问题描述】:

所以在我的 rails 应用程序中有列表。每个列表都有_一个项目。每个项目有_many 个项目。所以一个项目可以属于另一个项目。我想将这些资源呈现为 JSON,其中每个项目都有其嵌套在其下的子项目。由于每个项目都可能有自己的子项目,因此我不能只继续使用 include: 选项,因为我不知道最后一个项目何时没有子项目。

所以看起来我在呈现 JSON 时必须以某种方式使用递归,所以如果一个 Item 有子项,它的子项嵌套在它下面,如果这些子项中的任何一个有子项,则它们的子项嵌套在它们下面。

我不确定如何使用 to_json 和 include 选项来执行此操作。如果我只是渲染列表的第一个子项,我会这样做:

  respond_to do |format|
    format.json { render json: @list.to_json(include: :item) }
  end

但我不知道如何递归渲染 :item 的子项及其子项,等等。

另一个答案建议使用视图对象或像 RABL 这样的 gem 来解决对于 to_json 来说似乎太复杂的不同问题。对于 to_json 方法,我想要做的事情是否过于复杂?将子资源递归呈现为 json 的最佳选择是什么?

感谢您的帮助。

【问题讨论】:

    标签: ruby-on-rails ruby


    【解决方案1】:

    如果您可以使用自定义方法来准备 json,那么您可以这样做:

    class List
      has_one :item
    
      def custom_json
        json = to_json
        json[:item] = item.custom_json
        json
      end
    end
    
    class Item
      has_many :items # add other options
    
      def custom_json
        json = to_json.merge(children: [])
        items.each { |item| json[:children] << item.custom_json }
        json
      end
    end
    

    注意:这里的items 指的是您在Item 类中对其子项的关系。

    在你的控制器中,你可以这样做

    format.json { render json: @list.custom_json }
    

    这将导致 json 结构:

    { list_attr: value, list_attr_2: value, item: { item_attr: value, children: [{ child_item_attr: value, ... }] } }
    

    如果有帮助,请告诉我。

    【讨论】:

    • 谢谢我想通了。我以为我删除了这个问题,但你的回答是正确的,我会留下它,以防其他人在这方面感到困惑。
    • 你好。我想知道这个自定义方法应该在哪里(存储) - 在什么文件夹/文件中?我在stackoverflow.com/a/39340698/5730322 找到了一种渲染 json 的方法
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-05
    • 2013-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多