我正在尝试使用jbuilder gem来格式化json输出。
控制器
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
使用url:进行测试
http://localhost:5000/locations/tree.json
结果:
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
您在发布的代码中似乎没有定义@location
您应该迭代您的位置,jbuilder允许您这样做,例如:
Jbuilder.encode do |json|
json.locations @locations do |location|
json.id location.id
json.name location.name
end
end
如果您想要一个平面数组,请参阅文档。