当我尝试在终端中运行rails db:seed时,我遇到了问题。 它给了我以下错误:
你能帮帮我吗?到目前为止,我尝试了几件但没有运气。
NoMethodError
:未定义的方法`[]'为nil:NilClass
(1..50).each do |movie|
response = HTTParty.get("https://api.themoviedb.org/3/movie/popular?api_key=8d027704c57524153a0af2b38415ac45&language=en-US&page=1")
results = JSON.parse(response.body)
movie = Movie.new({
title: results["title"],
popularity: results[0]["popularity"],
image: results["poster_path"],
year: results[0]["release_date"],
genre: results[0]["genre_ids"]
})
movie.save
puts "#{movie['title']} was saved."
end
我的架构如下所示:
create_table "movies", force: :cascade do |t|
t.string "title"
t.string "image"
t.string "year"
t.string "genre"
t.string "rating"
t.string "popularity"
t.string "video"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
感谢您的帮助。
答案 0 :(得分:2)
JSON具有结构:
{
"page": 1,
"total_pages": 978,
"total_results": 19552,
"results": [..]
}
更改
results = JSON.parse(response.body)
要
results = JSON.parse(response.body)['results']
您的代码在其他地方也被破坏了。这是我的建议:
res = HTTParty.get('https://api.themoviedb.org/3/movie/popular?api_key=8d027704c57524153a0af2b38415ac45&language=en-US&page=1')
results = JSON.parse(res.body)['results']
results.each do |result|
movie = Movie.create({
title: result['title'],
popularity: result['popularity'],
image: result['poster_path'],
year: result['release_date'],
genre: result['genre_ids']
})
puts "#{movie.title} was saved."
end