Rails - 为json解析的值添加索引键

时间:2014-05-24 07:43:45

标签: ruby-on-rails json ruby-on-rails-4 indexing key

我正在使用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 objectarray

{
    "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

1 个答案:

答案 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