I am hitting a rails API for data which it returns as JSON; however, when I try to loop over it in ERB, I get an error because rails thinks the array is a string. Further, I guess I don't really know how to iterate over an array of hashes. I have searched for answers but can't seem to search correctly.
Sample of returned "string"/data:
[{"id":1,"name":"Hoodie","brand":"Ralph Lauren","price":50.0,"image":"work1.jpg",
"closetID":1,"occassion":"Casual","created_at":"2014-09-10T16:25:41.451Z",
"updated_at":"2014-09-10T16:25:41.451Z"},{"id":2,"name":"Pants","brand":"Lacoste",
"price":100.0,"image":"work2.jpg","closetID":1,"occassion":"Casual","created_at":
"2014-09-10T16:25:41.455Z","updated_at":"2014-09-10T16:25:41.455Z"},etc...]
I want to be able to loop over each set on my haml page. Any help is greatly appreciated - I am fairly new to Ruby/Rails. Sorry for any bad formatting/confusion. I can add more info if needed.
On the API end in items_controller.rb
def index
@items = Item.all
render json:items
end
From the calling end in main_controller.rb
def closet
require 'net/http'
url = URI.parse('http://localhost:3001/items')
req = Net::HTTP::Get.new(url.to_s)
res = Net::HTTP.start(url.host, url.port) {|http|
http.request(req)
}
@items = res.body
end
A simple call to =@items on the closet.html.haml page displays the above blob of 'string' data. It is on this page that I want to be able to display info from each hash.
Thank you!