2016-05-15 97 views
1

我有這樣的JSON數據(實際數據是長了不少,這就是爲什麼我只需要2)獲取特定的JSON數據軌

[ 
    { 
    "id": 1, 
    "user_id": 1, 
    "event_id": 1, 
    "creator_id": 1, 
    "event_name": "Poker", 
    "cruise_ship_name": "Royal Cruise", 
    }, 
    { 
    "id": 2, 
    "user_id": 1, 
    "event_id": 2, 
    "creator_id": 1, 
    "event_name": "Ballroom", 
    "cruise_ship_name": "Celebrity Infinity", 
    }, 
    { 
    "id": 3, 
    "user_id": 1, 
    "event_id": 3, 
    "creator_id": 1, 
    "event_name": "Tennis", 
    "cruise_ship_name": "Mediterranean", 
    } 
] 

我想所有的數據結合起來,得到的只是特定字段(EVENT_NAME和cruise_ship_name )

所以在我的最後JSON格式

這將是:

[ 
    { 
    "event_name": "Mexican Fiesta", 
    "cruise_ship_name": "Celebrity Infinity", 
    } 
] 

我有一直在看這個例子:

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

但不知道什麼:association_a和:association_b是。

+0

可能是這樣的副本:http://stackoverflow.com/questions/6919147/restrict-specific-fields-in-the-response-of-rails-controller – Jon

回答

0

假設你有散列的數組:

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 
0

to_json方法接受參數,讓你包括特定屬性:

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

include: :assocation_a選項以允許將assocation_a模型中的對象關聯轉換爲JSON。