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
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"}}]}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With