Question

TL;DR: How can i use jbuilder to create JSON that looks like this?

[
  {}, // Your new pagination state
  [{}, ...] // An array of JSON objects
]

Longer version:

I am trying get pagination working with Backbone.js and backbone-pageable https://github.com/wyuenho/backbone-pageable .

Backbone-pageable requires that the JSON returned be formatted such that it's an array of two objects. The first object is a regular object containing pagination control information. The second object should be an array of your actual data formatted as Backbone would normally expect. These expectations are hard coded into backbone-pageable's parse methods (source)

It seems weird to have an array of un-like items but for this use case it seems acceptable.

For json i've used rabl in the past but for science I'm trying to use jbuilder and I've gotten this far...

JSON structure (wrong):

{
  "current_page": 1,
  "total_pages": 6,
  ...,

  "entries": [
    { "id": 131 },
    ...
  ]
}

Using this code:

json.current_page @posts.current_page
...

json.entries @posts do |post|
  json.extract! post, :id...
end

Closer, but still very wrong :/

Thank you

Was it helpful?

Solution

Can you try this:

json.array! [0,1] do |index|
  if index == 0
    json.current_page @posts.current_page
    ...

  else
    json.entries @posts do |post|
      json.extract! post, :id...
    end
  end
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top