[英]NoMethodError: undefined method `[]' for nil:NilClass
I have a problem when I am trying to run rails db:seed in the terminal. 我在终端中尝试运行rails db:seed时遇到问题。 It's giving me the following error:
它给了我以下错误:
NoMethodError
: undefined method `[]' for nil:NilClassNoMethodError
:nil:NilClass的未定义方法“ []”
Can you please help me? 你能帮我么? I have tried several things but no luck so far.
到目前为止,我已经尝试了几件事,但是没有运气。
(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
My schema looks like this: 我的架构如下所示:
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
Thank you for your help. 谢谢您的帮助。
The JSON has structure: JSON具有以下结构:
{
"page": 1,
"total_pages": 978,
"total_results": 19552,
"results": [..]
}
Change 更改
results = JSON.parse(response.body)
To 至
results = JSON.parse(response.body)['results']
Your code is broken in other places too. 您的代码在其他地方也被破坏了。 Here is my suggestion:
这是我的建议:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.