简体   繁体   中英

Iterate over JSON Array in Rails5

I know I am missing something probably very obvious. I am trying to iterate over a JSON array in my Rails5 view. I tried several things but can't seem to get the proper items to render. The below code renders {"name"=>"Large Plaque", "price"=>"2500"} {"name"=>"Small Plaque", "price"=>"1500"} to my view.

config/plaque_data.json

{
  "products": [
    {
      "name": "Large Plaque",
      "price": "2500"
    },
    {
      "name": "Small Plaque",
      "price": "1500"
    }
  ]
}

controllers/plaqueorders_controller.rb

...
def new
 @plaqy = JSON.load File.read('config/plaque_data.json')
end
...

views/plaqueorders/new.html.erb

...
<% @plaqy['products'].each do |k, v| { name: k, price: v } %>
 <%= k %>
<% end %>
...

Since 'k' is a hash, you need to access k['name'] and k['price'] to extract price and name.

Also when you use .each on an array, you normally only declare one block argument (You have two, k and v ).

You normally write 2 block arguments for Hashes (and lots of other Enumerable methods), which is possibly what you thought you were iterating over, but

@plaqy['products']

is an array

Just to expand on the above answer, in your view you are iterating over an array, but treating it like a hash. So you might want to change your view to something like:

views/plaqueorders/new.html.erb

...
<% @plaqy['products'].each do |product|%>
 Name: <%= product['name'] %>
 Price: $<%= product['price'] %>
<% end %>
...

Obviously the block will change based on how you want to render each product, but something like that will work.

If you want to loop over the hashes because you don't know what the shape is (strange but okay), you'd want something like

...
<% @plaqy['products'].each do |product|%>
 <% product.each do |key, value| %>
   <%= key %>: <%= value %>
 <% end %>
<% end %>
...

Naming the variables of an each loop k, v is generally reserved for hashes. But in your code, the k wasn't the key of the hash but rather each individual product.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM