6

I have been trying to add custom attributes to jbuilder like i do in the show page to my index page for pagination with will paginate and its not displaying the custom attributes.

for example what i have in my controller action is

  def index
    #respond_with
    @publishers = Publisher.paginate(:page => params[:page], :per_page => 30)
    respond_to do |format|
      format.json
    end
  end

and my index.json.jbuilder is

json.array!(@publishers) do |publisher|
  json.extract! publisher, :id, :name, :url
  json.categories do
    publisher.categories.each do |category|
      json.name category.name
      json.id category.id
      json.url url_for(category)
    end
  end
end

what i would like to have is

json.current_page @publishers.current_page
json.total_pages @publishers.totla_entries

json.array!(@publishers) do |publisher|
  json.extract! publisher, :id, :name, :url
  json.categories do
    publisher.categories.each do |category|
      json.name category.name
      json.id category.id
      json.url url_for(category)
    end
  end
end

so that i have have the current_page and total pages showing up in the json output of the index page.

currently what i have is

[{"id":1,"name":"facebook","url":"http://www.facebook.com","categories":{"name":"Art and Crafts","id":1,"url":"/categories/1-art-and-crafts"}}]

how can i accomplish this. i am also using willpaginate

Uchenna
  • 4,059
  • 6
  • 40
  • 73

1 Answers1

11

After the long hustle, and taking a look at how the jbuilder show template works i realized that the json.array! method was overriding anything outside the block so i made a few tweeks and solved it by rapping it in a root node like below

json.current_page @publishers.current_page
json.total_pages @publishers.total_entries
json.total_records Publisher.count

json.publishers do |publishersElement|
  publishersElement.array!(@publishers) do |publisher|
    json.extract! publisher, :id, :name, :url
    json.categories do
      publisher.categories.each do |category|
        json.name category.name
        json.id category.id
        json.url url_for(category)
      end
    end
  end
end

and the output i got was this

{"current_page":1,"total_pages":1,"total_records":1,"publishers":[{"id":1,"name":"Bellanaija","url":"http://www.bellanaija.com","categories":{"name":"Art and Crafts","id":1,"url":"/categories/1-art-and-crafts"}}]}
Uchenna
  • 4,059
  • 6
  • 40
  • 73
  • 2
    Thanks for posting your answer, this helped me. I think two of your method are wrong. You should be using `json.total_pages @publishers.total_pages` and `json.total_records @publishers.total_records`. – flyingL123 Oct 29 '15 at 13:58
  • `@publishers.total_records` is fine so also `total_entries` used to work as at 2014 – Uchenna Oct 22 '16 at 02:49