【问题标题】:Rabl / Will Paginate setting name of root childRabl / Will Paginate 设置根孩子的名称
【发布时间】:2013-08-07 11:08:48
【问题描述】:

我想知道是否有人可以提供帮助。我正在尝试为我们的 API 迁移旧的 Rails Model#to_json,以便从长远来看更容易进行版本控制。由于 Rabl 和 Will Paginate,我在第一个障碍中挣扎。

我们目前覆盖 WillPaginate::Collection#as_json

module WillPaginate
  class Collection

    alias :as_json_without_paginate :as_json   

    def as_json(options = {})

      # RABL seemingly passing JSON::Ext::Generator::State into as_json
      unless options.is_a?(Hash)
        options = {}
      end

      json = {
        :page => current_page
        :per_page => per_page,
        :total_entries => total_entries,
        :entries => as_json_without_paginate(options)
      }
    end

  end
end

所以@collection.to_json 会返回类似

{
  "total_entries": 1,
  "page": 1,
  "entries": [
    {
      "follow": {
      "id": 1,
      "name": "TEST"
      }
    }
  ],
  "per_page": 10
}

但是当我尝试在 RABL 中执行以下操作时

node(:page) {|m| @follows.current_page }
node(:per_page) {|m| @follows.per_page }
node(:total_entries) {|m| @follows.total_entries}

child(@follows => :entries) do
  # extends 'follows/show'
  attributes :id, :name
end

孩子的名字自动设置为'entry',我想将其设置为'follow'以与我们当前的API保持一致但没有任何运气。

{
  "total_entries": 1,
  "page": 1,
  "entries": [
    {
      "entry": {
      "id": 1,
      "name": "TEST"
      }
    }
  ],
  "per_page": 10
}

任何人都可以给我任何指示。我一直在尝试追溯源头,似乎总是隐含子对象的根对象名称。

【问题讨论】:

    标签: json ruby-on-rails-3 api will-paginate rabl


    【解决方案1】:

    我遇到了同样的错误,问题似乎是将 object_root 设置为 false。这是我在回答另一个 stackoverflow 问题时提出的相同解决方案: wrong child root name in rabl and can't set child root name

    child( {@follow => :entries}, {:object_root => false} ) do
       # extends 'follows/show'
       attributes :id, :name
    end
    

    注意圆括号“()”和大括号“{}”。

    希望这会有所帮助。在我的情况下它工作得很好。

    【讨论】:

      【解决方案2】:

      :object_root => false 添加到您的child 块中应该可以做到。

      child(@follows => :entries, :object_root => false) do
        # extends 'follows/show'
        attributes :id, :name
      end
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-12-15
        • 2020-02-03
        • 2018-05-23
        • 1970-01-01
        • 2021-01-07
        • 2019-10-20
        • 2019-01-24
        相关资源
        最近更新 更多