Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 如何获得JSON格式的多层?_Ruby On Rails_Ruby_Json_Ruby On Rails 4_Database Design - Fatal编程技术网

Ruby on rails 如何获得JSON格式的多层?

Ruby on rails 如何获得JSON格式的多层?,ruby-on-rails,ruby,json,ruby-on-rails-4,database-design,Ruby On Rails,Ruby,Json,Ruby On Rails 4,Database Design,我正在使用rails 4.2和Ruby 2.1.5 我创建了两个表1.API(名称:string)和2.Description(键:string,值:string)。对于关系,API有很多数据 下面是我的控制器索引操作,用于返回JSON格式的数据 def show @api = Api.find(params[:id]) @descriptions = @api.descriptions.all data = {} @descriptions.each do |f| da

我正在使用rails 4.2和Ruby 2.1.5

我创建了两个表1.API(名称:string)和2.Description(键:string,值:string)。对于关系,API有很多数据

下面是我的控制器索引操作,用于返回JSON格式的数据

def show
  @api = Api.find(params[:id])
  @descriptions = @api.descriptions.all
  data = {}
  @descriptions.each do |f|
    data[f.key] = f.value
  end
  render json: data, :except => [:created_at, :id, :api_id ]
end
它可以返回JSON格式的数据,如:

{
  "country":"USA"
  "City":"NY"
}
我的问题是我应该如何获得下面这样的数据(多个JSON数据)


我应该如何重新设计我的数据库或任何其他方式

我建议为此实现模板处理程序。Ryan Bates在他们身上录制了一段精彩的视频,看看这个:(还有一个与github repo相关联的示例应用程序)

记住这一点,您只需结束呈现
json.rb
模板的控制器操作,该模板包含以下技巧:

# app/views/apis/show.json.rb

def list_of_countries
  @descriptions.inject({}) do |result, object|
    result[object["country"]] = object["city"]
    result
  end
  # => {"USA": "NY", "Great Britain": "London"}
end

{
  country: list_of_countries,
  password_type: @password_type # I assume you've set this up in controller
}.end.to_json
# {country: {"USA": "NY", "Great Britain": "London"}, password_type: "salt"}

你可以发布数据
@description
对象有吗?Descriptions表有两列(键和值)。在视图模板中,我设计了一个输入框,可以让用户在其中输入值。
# app/views/apis/show.json.rb

def list_of_countries
  @descriptions.inject({}) do |result, object|
    result[object["country"]] = object["city"]
    result
  end
  # => {"USA": "NY", "Great Britain": "London"}
end

{
  country: list_of_countries,
  password_type: @password_type # I assume you've set this up in controller
}.end.to_json
# {country: {"USA": "NY", "Great Britain": "London"}, password_type: "salt"}