1

誰か助けてくれませんか。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」に設定されます。現在の API と一致するように「follow」に設定したいのですが、うまくいきません。

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

誰でも私に何か指針を与えることができますか?ソースをさかのぼって追跡しようとしましたが、子のルート オブジェクト名の名前が常に暗示されているようです。

4

2 に答える 2

3

私はまったく同じバグに遭遇しました。問題は object_root を false に設定しているようです。別のスタックオーバーフローの質問に応えて提案したのと同じ解決策を次に示します: rabl の間違った子ルート名と子ルート名を設定できません

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

丸括弧 "()" と中括弧 "{}" の両方に注意してください。

お役に立てれば。私の場合は完璧に機能しました。

于 2013-11-01T20:25:29.437 に答える
0

:object_root => falseあなたのchildブロックに追加することでそれができるはずです。

child(@follows => :entries, :object_root => false) do
  # extends 'follows/show'
  attributes :id, :name
end
于 2013-09-26T05:17:18.617 に答える