2016-05-15 7 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 ]} 

ただし、what: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に変換することもできます。

関連する問題