1

I have this json data (actual data is a lot longer, that's why I need only 2)

 [
  {
    "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",
  }
]

I want to combine all data and get only specific fields (event_name and cruise_ship_name)

So in my final json format

it will be:

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

I have been looking at this example:

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

but not sure what :association_a and :association_b are.

Graham Slick
  • 6,692
  • 9
  • 51
  • 87
XDProgrammer
  • 853
  • 2
  • 14
  • 31
  • Possibly a duplicate of this: http://stackoverflow.com/questions/6919147/restrict-specific-fields-in-the-response-of-rails-controller – Jon May 15 '16 at 06:09

2 Answers2

0

Suppose you have an array of hashes:

events = [
  {
    "id": 1,
    "user_id": 1,
    "event_id": 1,
    "creator_id": 1,
    "event_name": "Poker",
    "cruise_ship_name": "Royal Cruise",
  },
  ...
]

You can iterate through each value in your hash, only keeping values of interest:

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

puts events
Anthony E
  • 11,072
  • 2
  • 24
  • 44
0

The to_json method accept parameters which allow you include specific attributes:

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

The include: :assocation_a option to object, allowing the object association in the assocation_a model to be converted to JSON as well.

Roman Kiselenko
  • 43,210
  • 9
  • 91
  • 103