我想要做的是通过哈希循环并将某些键的值保存到数据库。这个散列有嵌套的关键字,我努力寻找一种合适的方式来循环它。循环遍历Rails控制器中的嵌套哈希
首先,我解析照片的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'
这样做完美。非常感谢! – gosseti