Question

I'm trying to use jbuilder gem to format json output.

Controller

class LocationsController < ApplicationController
def tree
  @locations = Location.all
end

tree.json.jbuilder

Jbuilder.encode do |json|
  json.id @location.id
  json.name @location.name
end

Test using url:

http://localhost:5000/locations/tree.json

Results:

Called id for nil, which would mistakenly be 4 -- if you really wanted the id of nil, use object_id
Extracted source (around line #2):

1: Jbuilder.encode do |json|
2:   json.id @location.id
3:   json.name @location.name
4: end
Was it helpful?

Solution

you don't seem to define @location in the code you have posted.
you should iterate over your locations, jbuilder lets you do it for example like this:

Jbuilder.encode do |json|
  json.locations @locations do |location|
    json.id location.id
    json.name location.name
  end
end

see the docs if you want a flat array instead.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top