Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/57.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_Json - Fatal编程技术网

Ruby on rails 获取特定的json数据轨道

Ruby on rails 获取特定的json数据轨道,ruby-on-rails,json,Ruby On Rails,Json,我有这个json数据(实际数据要长得多,所以我只需要2个) 我想合并所有数据,只获取特定字段(事件名称和巡航船舶名称) 所以在我最后的json格式中 它将是: [ { "event_name": "Mexican Fiesta", "cruise_ship_name": "Celebrity Infinity", } ] 我一直在看这个例子: @object.to_json {:include => [ :assocation_a, :assocation_b ]}

我有这个json数据(实际数据要长得多,所以我只需要2个)

我想合并所有数据,只获取特定字段(事件名称和巡航船舶名称)

所以在我最后的json格式中

它将是:

[
  {
   "event_name": "Mexican Fiesta",
   "cruise_ship_name": "Celebrity Infinity",
  }
]
我一直在看这个例子:

@object.to_json {:include => [ :assocation_a, :assocation_b ]} 

但不确定:association\u a和:association\u b是什么。

假设您有一个哈希数组:

events = [
  {
    "id": 1,
    "user_id": 1,
    "event_id": 1,
    "creator_id": 1,
    "event_name": "Poker",
    "cruise_ship_name": "Royal Cruise",
  },
  ...
]
您可以迭代哈希中的每个值,只保留感兴趣的值:

events.each do |event_hash| 
   event_hash.keep_if { |key, _| [:event_name, :cruise_ship_name].include?(key) }
end

puts events

假设您有一个哈希数组:

events = [
  {
    "id": 1,
    "user_id": 1,
    "event_id": 1,
    "creator_id": 1,
    "event_name": "Poker",
    "cruise_ship_name": "Royal Cruise",
  },
  ...
]
您可以迭代哈希中的每个值,只保留感兴趣的值:

events.each do |event_hash| 
   event_hash.keep_if { |key, _| [:event_name, :cruise_ship_name].include?(key) }
end

puts events
该方法接受允许您包含特定属性的参数:

@object.to_json(only: [:event_name, :cruise_ship_name])
include::association\u a
选项用于对象,允许将
association\u a
模型中的对象关联也转换为JSON。

该方法接受允许您包含特定属性的参数:

@object.to_json(only: [:event_name, :cruise_ship_name])

include::association\u a
选项用于对象,允许将
association\u a
模型中的对象关联也转换为JSON。

可能是此的副本:可能是此的副本: