I'm learning Ruby and Rails, and the tutorials have been saying I should set everything up in the controller first for what my ERB file is going to need. I'm having some issues doing that.
I'm getting a product catalog from an API and I'm getting back an array. Here's the start of it:
[{"Name"=>"3x4 Vinyl Magnet", "Description"=>"Made of durable high-gloss vinyl. Measures 3x4 inches and has rounded corners. Waterproof and scratch resistant.", "UnitPrice"=>8.99, "ProductCode"=>"Gift65001"
There are more multiple products.
In my controller file I have:
@http_party_json = JSON.parse(@response.body)
@http_party_json.each do |i|
i.each do |x|
@just_products = x['Products']
end
end
@just_products.each do |grab|
@product_code = grab['ProductCode']; @product_code.delete! ';'
@just_names = grab['Name']
@just_prices = grab['UnitPrice']
@just_descriptions = grab['Description']
end
My ERB file is:
<div class="large-12 columns">
<div class="row">
<% @just_products.each do %>
<div class="large-3 columns panel radius" style="height: 600px"><h2><%= @just_names %></h2><br><h3><%= @just_prices %></h3><br>
<p><%= @just_descriptions %></p>
<button id="<%= @product_code %>">Add to Cart</button>
</div>
<% end %>
</div>
It's displaying the last item in the array for each result it's bringing back. If I transfer the grab loop from the controller to the ERB file, it works fine, but I want to learn how to do it correctly.
<% @just_products.each do %>you have no|product|, so the loop is looping but not handing a product to the "inside" of the loop. If you use<% @just_products.each do |product| %>it will pass each item in the array to the loop. You then access their methods with<%= product.name %>and<%= product.description %>. edit I just realized you are not loading them from the DB.