David
David

Reputation: 652

Rails says my array of hashes is a string; I need to loop over this array

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!

Upvotes: 0

Views: 429

Answers (2)

nPn
nPn

Reputation: 16728

I think the right way to do this would have been to change the controller so that it responds differently for html vs json. rather than basically undoing the json rendering in the view. So something like this:

def index
  @items = Item.all
    respond_to do |format|
      format.html
      format.json { render :json => @items.to_json }
    end
end

Upvotes: 1

usha
usha

Reputation: 29349

You should parse the JSON before assigning it to @items. Use any one of the available JSON libraries like json

@items = JSON.parse(res.body)

now in your view, you can iterate it like

<%@items.each do |item|%>
  <%= item["name"]%>
  <%= item["brand"]%>
<%end%>

Upvotes: 2

Related Questions