我正在使用rails 4.0.2
。对于我的mobile api
,我需要向其发送JSON
个值。在这里,我遇到了发送JSON
的一些问题。我想使用JSON
index key
例如,当我请求index
控制器的cities
时,
http:localhost:3000/cities.json
我得到JSON
这样的值,
[
{"id":1,"name":"AAAA"},
{"id":2,"name":"BBBB"},
{"id":2,"name":"CCCC"}
]
但我希望包含一些named object
或array
。
{
"cities" :
[
{"id":1,"name":"AAAA"},
{"id":2,"name":"BBBB"},
{"id":2,"name":"CCCC"}
]
}
现在我在我的控制器中试过了,
def index
@cities = City.all
respond_to do |format|
format.html
format.json{ render :json => @cities.to_json(:methods => [:image_url]) }
# :methods => [:image_url] this is related to paperclip gem
end
end
答案 0 :(得分:1)
首先尝试: -
def index
@cities = City.all
cit ={'cities' => @cities}
respond_to do |format|
format.html
format.json{ render :json => cit}
end
end
之后尝试: -
def index
@cities = City.all
cit ={'cities' => @cities}
respond_to do |format|
format.html
format.json{ render :json => cit.to_json(:methods => [:image_url]) }
end
end