What I’m trying to do is loop through a hash and save certain key’s values to the database. This hash has nested keys, and I’m struggling to find a suitable way to loop through it.
First, I’m parsing the JSON of photos (from 500px API), and putting the response into terminal:
def index
@photos = JSON.parse(get_access_token.get('/v1/photos/search?term=california').body)
p @photos
save @photos
end
The response I get in console is all okay and looks like this. (I’ve cut it down so it doesn’t take up too much room):
{
"current_page": 1,
"total_pages": 50,
"total_items": 8263,
"photos": [
{
"id": 4930535,
"name": "Bike",
"description": "",
"times_viewed": 28,
"rating": 27,
"created_at": "2012-02-10T00:39:03-05:00"
},
{
"id": 4930206,
"name": "Rain",
"description": "",
"times_viewed": 1,
"rating": 59.7,
"created_at": "2012-02-10T00:04:09-05:00"
},
{
"id": 4930202,
"name": "California",
"description": "",
"times_viewed": 100,
"rating": 58.2,
"created_at": "2012-02-10T00:05:25-05:00"
}
]
}
I’m then trying to loop through the photos and save the name, description and times_viewed to the db, using this save method.
def save photos
photos.each do |photo|
p = Photo.new(:name => photo["photos"]["name"], :description => photo["photos"]["description"], :times_viewed => photo["photos"]["times_viewed"])
p.save
end
end
The trouble is that the photos key is nested, and it throws this error in terminal:
TypeError (no implicit conversion of String into Integer):
app/controllers/photos_controller.rb:18:in `[]'
app/controllers/photos_controller.rb:18:in `block in save'
app/controllers/photos_controller.rb:17:in `each'
app/controllers/photos_controller.rb:17:in `save'
app/controllers/photos_controller.rb:10:in `index'