我要做的是循环哈希并将某些键的值保存到数据库中。这个哈希有嵌套键,我很难找到一种合适的方法来循环它。
首先,我正在解析照片的JSON(来自500px API),并将响应放入终端:
def index
@photos = JSON.parse(get_access_token.get('/v1/photos/search?term=california').body)
p @photos
save @photos
end
我在控制台中得到的响应都没问题,看起来像这样。 (我把它剪掉了所以不占用太多空间):
{
"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"
}
]
}
然后我尝试遍历photos
并使用此保存方法将name
,description
和times_viewed
保存到数据库。
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
问题是照片键是嵌套的,它会在终端中抛出此错误:
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'
答案 0 :(得分:3)
只需从你的json响应中取出照片数组并迭代它。这样,您只需要一层哈希键来引用:
json_response['photos'].each do |photo|
Photo.create name: photo['name'], description: photo['description'],
times_viewed: photo['times_viewed']
end
答案 1 :(得分:0)
photos["photos"]
是一个数组,因此您需要在name
之前指定索引。保存方法的实现并不完全清楚,但我相信新方法的参数应该采用以下形式:
:name => photo["photos"][index]["name"]
由于编译器尝试将name
转换为索引,因此您收到转换错误。