Raphael Onofre
Raphael Onofre

Reputation: 304

Dynamically display hashes/data/JSON in the view

I'm trying to dynamically insert headers and tbody into the HTML using Ruby and Sinatra. Until the moment i've got the headers but i'm not having success on the body.

Here's my code:

get '/list' do
 urlData = "http://localhost:3000/data"
 responseData = RestClient.get urlData

 @banks = JSON.parse(responseData.body)
 @keys = @banks[0].keys # OK
 @values =  @banks.map(&:values) # Trying to put in the html

 erb :list

end

The view, as follows:

<thead>
 <tr>
  <% @keys.each do |key| %>
   <th><%= key %></th>
  <% end %>
 </tr>
</thead>

<tbody>
 <% @values.each do |value| %>
  <tr>
   <td><%= value %></td>
  </tr>
 <% end %>
</tbody>

The JSON format:

[
 {
  "ID": 247,
  "Code": "246",
  "Name": "ABC BANK S.A."
 },
 {
  "ID": 248,
  "Code": "25",
  "Name": "Beta Bank"
 }, ...
]

How is displaying: enter image description here A way to solve is placing kind of a increment, like

<%= value[0] %>

but i can't find an elegant way.

Upvotes: 1

Views: 119

Answers (1)

peter
peter

Reputation: 42192

If I understand you correctly, you want to show the values in separate td tags, you can do that like this. The @values is an array of arrays (the rows) which contain the cell values.

<tbody>
 <% @values.each do |row| %>
  <tr>
    <% row.each do |value| %>
     <td><%= value %></td>
    <%end%>
  </tr>
 <% end %>
</tbody>

EDIT: you get your array of arrays like this

banks.map{|x| x.values}
#[[247, "246", "ABC BANK S.A."], [248, "25", "Beta Bank"]]

and you pass it to your view like this, not sure if necessary

erb :list, :locals => {values: @values, keys: @keys}

Upvotes: 1

Related Questions