1

我有一些像这样输出 JSON 的 Ruby 代码:

def nearby
  #@bathrooms = Bathroom.geo_scope(:origin =>[params[:lat],[params[:lon]]], :within => 5)
  lat = params[:lat]
  lon = params[:lon]
  #@bathrooms = Bathroom.geo_scope(:within => 5, :origin => [45.580639,-122.677682], :order=>'distance')
  @bathrooms = Bathroom.geo_scope(:within => 3, :origin => [lat,lon], :order=>'distance')
  respond_to do |format|
    format.json  { render :json => @bathrooms }
    format.js   { render :nothing => true } 
  end   
end

结果是这样的:

 [{"ID":129,"access":"1","avail":"0","bathroomtype":"0","city":"PORTLAND","comment":"","country":"US","created":"0000-00-00 00:00:00","directions":"The two bathrooms are in the long hallway at the back of the restaurant, past the bar.","distance":"2.94986114636676","lat":"45.539217","lon":"-122.661795","modifed":"0000-00-00","name":"Echo","postal":"97212-3727","slug":"echo-portland170","source":"","state":"OR","street":"2225 NE Martin Luther King Jr. Blvd"},

我不知道该怎么做就是给集合命名?例如,在第一个封闭括号之后,我想命名设置的浴室。我怎么能做到这一点是Rails?

4

2 回答 2

1

尝试:

render json: { bathrooms: @bathrooms }
于 2012-11-05T21:20:44.633 回答
0

看起来@bathrooms 是一个列表,因此您不能将键分配给列表中的元素。您需要先制作地图。例如,如果您只想要第一个元素:

format.json { render :json => {:bathrooms => @bathrooms[0]} }

设置所有列表元素:

format.json { render :json => {:bathrooms => @bathrooms} }
于 2012-11-05T21:24:10.830 回答