rapidash
rapidash

Reputation: 278

Displaying an object with Ruby on Rails

I have some JSON that looks like this. I have it stored and read into an object, @items.

[
 {
  {
    "id": "A",
    "description": "a_description"
  }, 
  {
    "id": "B",
    "description": "b_description"
  }
 }, 
 {
  {
    "id": "A",
    "description": "a_description"
  }, 
  {
    "id": "B",
    "description": "b_description"
  }
 }
] 

My goal is to display a table with two columns, one labeled A and the other labeled B, in which each row gives the "a_description" and "b_description". I'm not sure how to go about doing this.

Upvotes: 1

Views: 92

Answers (2)

Ron
Ron

Reputation: 1166

Ah, the ol' array of hashes and hashes of arrays problem.

To get around your "out of order" problem you first have to convert

{
  "id": "A",
  "description": "foo"
},
{
  "id": "B",
  "description": "bar"
}

into {"A" : "foo", "B" : "bar" }.

@new_items = @items.map do |item|
  output = {}
  item.each do |hash|
    output.merge!(hash["id"] => hash["description"])
  end
end

Then @new_items becomes (intentionally presented out of order since hash elements are not ordered)

[
  { 
    "A": "a1_description",
    "B": "b1_description"
  },
  { 
    "B": "b2_description",
    "A": "a2_description"
  }
]

From there, each line is simply a hash, so you can just dereference the value you need based on the column you're in.

@new_items.each do |item|
  puts "#{item['A']} is paired with #{item['B']}"
end

Keys, of course could be retrieved dynamically if you don't want to hard code "A" and "B" using .keys

Upvotes: 2

Sully
Sully

Reputation: 14943

Something like this maybe

<tr><th>A</th><th>B</th></tr>
<% @items.each do |item| %>
  <tr><td><%=item[0].description%></td><td><%=item[1].description%></td></tr>
<% end %>

Upvotes: 2

Related Questions