質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
Ruby

Rubyはプログラミング言語のひとつで、オープンソース、オブジェクト指向のプログラミング開発に対応しています。

Ruby on Rails 6

Ruby on Rails 6は、オープンソースのWebアプリケーションフレームワークです。「同じことを繰り返さない」というRailsの基本理念のもと、他のフレームワークより少ないコードで簡単に開発できるよう設計されています。

Q&A

解決済

2回答

623閲覧

NoMethodError (undefined method `[]' for nil:NilClassを解決したい

masakingu

総合スコア11

Ruby

Rubyはプログラミング言語のひとつで、オープンソース、オブジェクト指向のプログラミング開発に対応しています。

Ruby on Rails 6

Ruby on Rails 6は、オープンソースのWebアプリケーションフレームワークです。「同じことを繰り返さない」というRailsの基本理念のもと、他のフレームワークより少ないコードで簡単に開発できるよう設計されています。

0グッド

0クリップ

投稿2023/01/10 22:03

編集2023/01/15 22:01

前提

APIを使用して、サッカーの選手を検索できるように実装にしているのですが、エラーメッセージが出ました。

実現したいこと

エラーを解決して、レスポンスをviewに表示させたいです。

発生している問題・エラーメッセージ

Started GET "/players/search?season=2018&player_name=cavani&commit=%E6%A4%9C%E7%B4%A2" for ::1 at 2023-01-10 07:08:29 +0900 Processing by PlayersController#search as HTML Parameters: {"season"=>"2018", "player_name"=>"cavani", "commit"=>"検索"} {"get":"players","parameters":{"search":"cavani","team":"85"},"errors":[],"results":1,"paging":{"current":1,"total":1},"response":[{"player":{"id":274,"name":"E. Cavani","firstname":"Edinson Roberto","lastname":"Cavani G\u00f3mez","age":36,"birth":{"date":"1987-02-14","place":"Salto","country":"Uruguay"},"nationality":"Uruguay","height":"184 cm","weight":"71 kg","injured":false,"photo":"https:\/\/media-3.api-sports.io\/football\/players\/274.png"},"statistics":[{"team":{"id":85,"name":"Paris Saint Germain","logo":"https:\/\/media-2.api-sports.io\/football\/teams\/85.png"},"league":{"id":61,"name":"Ligue 1","country":"France","logo":"https:\/\/media-1.api-sports.io\/football\/leagues\/61.png","flag":"https:\/\/media-1.api-sports.io\/flags\/fr.svg","season":2019},"games":{"appearences":14,"lineups":7,"minutes":602,"number":null,"position":"Attacker","rating":"6.607692","captain":false},"substitutes":{"in":7,"out":4,"bench":9},"shots":{"total":28,"on":11},"goals":{"total":4,"conceded":null,"assists":1,"saves":null},"passes":{"total":111,"key":9,"accuracy":78},"tackles":{"total":4,"blocks":0,"interceptions":1},"duels":{"total":null,"won":null},"dribbles":{"attempts":8,"success":7,"past":null},"fouls":{"drawn":2,"committed":8},"cards":{"yellow":2,"yellowred":0,"red":0},"penalty":{"won":null,"commited":null,"scored":1,"missed":0,"saved":null}},{"team":{"id":85,"name":"Paris Saint Germain","logo":"https:\/\/media-1.api-sports.io\/football\/teams\/85.png"},"league":{"id":61,"name":"Ligue 1","country":"France","logo":"https:\/\/media-1.api-sports.io\/football\/leagues\/61.png","flag":"https:\/\/media-2.api-sports.io\/flags\/fr.svg","season":2018},"games": #一部割愛 NoMethodError (undefined method `[]' for nil:NilClass @player_name = response["response"][0]["player"]["name"] ^^^): app/controllers/players_controller.rb:68:in `search'

ターミナルでレスポンスは帰って来ますが、viewに表示できません。

該当のソースコード

players_controller.rb

class PlayersController < ApplicationController require 'uri' require 'net/http' require 'openssl' require 'json' before_action :set_q, only: %i[search] def search url = URI.parse('https://api-football-v1p.rapidapi.com/v3/players?team=85&search=cavani') http = Net::HTTP.new(url.host, url.port) http.use_ssl = true http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Get.new(url) request["x-rapidapi-host"] = 'api-football-v1.p.rapidapi.com' request["x-rapidapi-key"] = 'API KEY' response = http.request(request) puts response.read_body result = JSON.parse(response.read_body) @player_name = response["response"][0]["player"]["name"] @team = response["response"][0]["statistics"][0]["team"]["name"] @age = response["response"][0]["player"]["age"] @natinality = response["response"][0]["player"]["nationality"] end private def set_q @q = User.ransack(params[:q]) end # Use callbacks to share common setup or constraints between actions. def set_player @player = Player.find(params[:player_id]) end # Only allow a list of trusted parameters through. def player_params params.require(:player).permit(:player_name, :season) end def search_params params[:q]&.permit(:player_name, :season) end end

players/search.html.erb

<div class="container"> <div class="row"> <div class="col-lg-8 offset-lg-2"> <div class="player"> <%= form_with url: search_players_path, method: :get, local: true do |f| %> <div class="form-group"> <h1>プレイヤー検索</h1> <%= f.text_field :season, class: 'form-control', placeholder: '西暦を入力してください(例: 1997)' %> <div class="search2 "> <%= f.text_field :player_name, class: 'form-control', placeholder: '選手名を入力してください' %> <%= f.submit '検索', class: 'btn btn-primary' %> </div> </div> <% if @player_name.present? %> <%= render 'players/player' %> <% end %> <% end %> </div> </div> </div> </div>

_player.html.erb

<div class="container"> <div class="row"> <div class="col-lg-8 offset-lg-2"> <h1>player</h1> <div> <% if @player.present? %> <table> <tr> <td>プレイヤー名</td> <td><%= @player_name %></td> </tr> <tr> <td>チーム名</td> <td><%= @team%></td> </tr> <tr> <td>年齢</td> <td><%= @age%></td> </tr> <tr> <td>国籍</td> <td><%= @natinality%></td> </tr> </table> <% end %> </div> </div> </div> </div>

試したこと

[]の中のデータが正常にデータが取得できてないとは、わかりますが、
原因が特定できません。

補足情報(FW/ツールのバージョンなど)

API :https://www.api-football.com/documentation-v3#tag/Players/operation/get-players-seasons

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

yuma.inaura

2023/01/11 00:03

responseはどんな中身になってるんでしょう
yuma.inaura

2023/01/13 13:06

テキストで載せていただければと、、
masakingu

2023/01/13 18:42 編集

みづらいですが、このようになっています。 ``` Started GET "/players/search?season=2018&player_name=cavani&commit=%E6%A4%9C%E7%B4%A2" for ::1 at 2023-01-12 12:52:15 +0900 Processing by PlayersController#search as HTML Parameters: {"season"=>"2018", "player_name"=>"cavani", "commit"=>"検索"} {"get":"players","parameters":{"search":"cavani","team":"85"},"errors":[],"results":1,"paging":{"current":1,"total":1},"response":[{"player":{"id":274,"name":"E. Cavani","firstname":"Edinson Roberto","lastname":"Cavani G\u00f3mez","age":36,"birth":{"date":"1987-02-14","place":"Salto","country":"Uruguay"},"nationality":"Uruguay","height":"184 cm","weight":"71 kg","injured":false,"photo":"https:\/\/media-1.api-sports.io\/football\/players\/274.png"},"statistics":[{"team":{"id":85,"name":"Paris Saint Germain","logo":"https:\/\/media-1.api-sports.io\/football\/teams\/85.png"},"league":{"id":61,"name":"Ligue 1","country":"France","logo":"https:\/\/media-3.api-sports.io\/football\/leagues\/61.png","flag":"https:\/\/media-2.api-sports.io\/flags\/fr.svg","season":2019},"games":{"appearences":14,"lineups":7,"minutes":602,"number":null,"position":"Attacker","rating":"6.607692","captain":false},"substitutes":{"in":7,"out":4,"bench":9},"shots":{"total":28,"on":11},"goals":{"total":4,"conceded":null,"assists":1,"saves":null},"passes":{"total":111,"key":9,"accuracy":78},"tackles":{"total":4,"blocks":0,"interceptions":1},"duels":{"total":null,"won":null},"dribbles":{"attempts":8,"success":7,"past":null},"fouls":{"drawn":2,"committed":8},"cards":{"yellow":2,"yellowred":0,"red":0},"penalty":{"won":null,"commited":null,"scored":1,"missed":0,"saved":null}},{"team":{"id":85,"name":"Paris Saint Germain","logo":"https:\/\/media-1.api-sports.io\/football\/teams\/85.png"},"league":{"id":61,"name":"Ligue 1","country":"France","logo":"https:\/\/media-2.api-sports.io\/football\/leagues\/61.png","flag":"https:\/\/media-1.api-sports.io\/flags\/fr.svg","season":2018},"games":{"appearences":21,"lineups":20,"minutes":1676,"number":null,"position":"Attacker","rating":"7.400000","captain":false},"substitutes":{"in":1,"out":6,"bench":3},"shots":{"total":52,"on":24},"goals":{"total":18,"conceded":null,"assists":5,"saves":null},"passes":{"total":267,"key":13,"accuracy":77},"tackles":{"total":9,"blocks":2,"interceptions":6},"duels":{"total":96,"won":42},"dribbles":{"attempts":20,"success":11,"past":null},"fouls":{"drawn":16,"committed":11},"cards":{"yellow":1,"yellowred":0,"red":0},"penalty":{"won":2,"commited":null,"scored":4,"missed":1,"saved":null}},{"team":{"id":85,"name":"Paris Saint Germain","logo":"https:\/\/media-2.api-sports.io\/football\/teams\/85.png"},"league":{"id":61,"name":"Ligue 1","country":"France","logo":"https:\/\/media-3.api-sports.io\/football\/leagues\/61.png","flag":"https:\/\/media-1.api-sports.io\/flags\/fr.svg","season":2017},"games":{"appearences":32,"lineups":30,"minutes":2588,"number":null,"position":"Attacker","rating":"7.531250","captain":false},"substitutes":{"in":2,"out":10,"bench":2},"shots":{"total":105,"on":56},"goals":{"total":28,"conceded":null,"assists":6,"saves":null},"passes":{"total":408,"key":40,"accuracy":78},"tackles":{"total":1,"blocks":0,"interceptions":5},"duels":{"total":124,"won":58},"dribbles":{"attempts":26,"success":15,"past":null},"fouls":{"drawn":20,"committed":19},"cards":{"yellow":3,"yellowred":0,"red":0},"penalty":{"won":3,"commited":null,"scored":3,"missed":2,"saved":null}},{"team":{"id":85,"name":"Paris Saint Germain","logo":"https:\/\/media-3.api-sports.io\/football\/teams\/85.png"},"league":{"id":61,"name":"Ligue 1","country":"France","logo":"https:\/\/media-1.api-sports.io\/football\/leagues\/61.png","flag":"https:\/\/media-2.api-sports.io\/flags\/fr.svg","season":2016},"games":{"appearences":36,"lineups":35,"minutes":2976,"number":null,"position":"Attacker","rating":"7.286111","captain":false},"substitutes":{"in":1,"out":13,"bench":2},"shots":{"total":144,"on":66},"goals":{"total":35,"conceded":null,"assists":4,"saves":null},"passes":{"total":425,"key":26,"accuracy":81},"tackles":{"total":null,"blocks":null,"interceptions":12},"duels":{"total":130,"won":51},"dribbles":{"attempts":16,"success":7,"past":null},"fouls":{"drawn":11,"committed":25},"cards":{"yellow":5,"yellowred":0,"red":0},"penalty":{"won":2,"commited":null,"scored":7,"missed":1,"saved":null}},{"team":{"id":85,"name":"Paris Saint Germain","logo":"https:\/\/media-3.api-sports.io\/football\/teams\/85.png"},"league":{"id":61,"name":"Ligue 1","country":"France","logo":"https:\/\/media-1.api-sports.io\/football\/leagues\/61.png","flag":"https:\/\/media-2.api-sports.io\/flags\/fr.svg","season":2015},"games":{"appearences":32,"lineups":24,"minutes":2305,"number":null,"position":"Attacker","rating":"7.237500","captain":false},"substitutes":{"in":8,"out":4,"bench":10},"shots":{"total":81,"on":45},"goals":{"total":19,"conceded":0,"assists":5,"saves":null},"passes":{"total":715,"key":26,"accuracy":61},"tackles":{"total":20,"blocks":5,"interceptions":13},"duels":{"total":161,"won":70},"dribbles":{"attempts":24,"success":18,"past":null},"fouls":{"drawn":22,"committed":30},"cards":{"yellow":3,"yellowred":0,"red":0},"penalty":{"won":1,"commited":null,"scored":0,"missed":1,"saved":null}},{"team":{"id":85,"name":"Paris Saint Germain","logo":"https:\/\/media-2.api-sports.io\/football\/teams\/85.png"},"league":{"id":61,"name":"Ligue 1","country":"France","logo":"https:\/\/media-3.api-sports.io\/football\/leagues\/61.png","flag":"https:\/\/media-1.api-sports.io\/flags\/fr.svg","season":2014},"games":{"appearences":35,"lineups":30,"minutes":2630,"number":null,"position":"Attacker","rating":null,"captain":false},"substitutes":{"in":5,"out":7,"bench":6},"shots":{"total":null,"on":null},"goals":{"total":18,"conceded":null,"assists":null,"saves":null},"passes":{"total":null,"key":null,"accuracy":null},"tackles":{"total":null,"blocks":null,"interceptions":null},"duels":{"total":null,"won":null},"dribbles":{"attempts":null,"success":null,"past":null},"fouls":{"drawn":null,"committed":null},"cards":{"yellow":3,"yellowred":1,"red":0},"penalty":{"won":null,"commited":null,"scored":null,"missed":null,"saved":null}},{"team":{"id":85,"name":"Paris Saint Germain","logo":"https:\/\/media-3.api-sports.io\/football\/teams\/85.png"},"league":{"id":61,"name":"Ligue 1","country":"France","logo":"https:\/\/media-1.api-sports.io\/football\/leagues\/61.png","flag":"https:\/\/media-1.api-sports.io\/flags\/fr.svg","season":2013},"games":{"appearences":30,"lineups":25,"minutes":2297,"number":null,"position":"Attacker","rating":null,"captain":false},"substitutes":{"in":5,"out":5,"bench":6},"shots":{"total":null,"on":null},"goals":{"total":16,"conceded":null,"assists":null,"saves":null},"passes":{"total":null,"key":null,"accuracy":null},"tackles":{"total":null,"blocks":null,"interceptions":null},"duels":{"total":null,"won":null},"dribbles":{"attempts":null,"success":null,"past":null},"fouls":{"drawn":null,"committed":null},"cards":{"yellow":2,"yellowred":0,"red":0},"penalty":{"won":null,"commited":null,"scored":null,"missed":null,"saved":null}},{"team":{"id":85,"name":"Paris Saint Germain","logo":"https:\/\/media-2.api-sports.io\/football\/teams\/85.png"},"league":{"id":65,"name":"Coupe de la Ligue","country":"France","logo":"https:\/\/media-1.api-sports.io\/football\/leagues\/65.png","flag":"https:\/\/media-2.api-sports.io\/flags\/fr.svg","season":2019},"games":{"appearences":1,"lineups":0,"minutes":18,"number":null,"position":"Attacker","rating":"6.800000","captain":false},"substitutes":{"in":1,"out":0,"bench":1},"shots":{"total":1,"on":0},"goals":{"total":0,"conceded":null,"assists":null,"saves":null},"passes":{"total":3,"key":1,"accuracy":60},"tackles":{"total":1,"blocks":0,"interceptions":0},"duels":{"total":null,"won":null},"dribbles":{"attempts":0,"success":0,"past":null},"fouls":{"drawn":0,"committed":0},"cards":{"yellow":0,"yellowred":0,"red":0},"penalty":{"won":null,"commited":null,"scored":0,"missed":0,"saved":null}},{"team":{"id":85,"name":"Paris Saint Germain","logo":"https:\/\/media-1.api-sports.io\/football\/teams\/85.png"},"league":{"id":66,"name":"Coupe de France","country":"France","logo":"https:\/\/media-2.api-sports.io\/football\/leagues\/66.png","flag":"https:\/\/media-3.api-sports.io\/flags\/fr.svg","season":2019},"games":{"appearences":3,"lineups":3,"minutes":256,"number":null,"position":"Attacker","rating":"7.533333","captain":false},"substitutes":{"in":0,"out":1,"bench":0},"shots":{"total":13,"on":7},"goals":{"total":2,"conceded":null,"assists":1,"saves":null},"passes":{"total":46,"key":2,"accuracy":73},"tackles":{"total":3,"blocks":2,"interceptions":2},"duels":{"total":null,"won":null},"dribbles":{"attempts":2,"success":1,"past":null},"fouls":{"drawn":3,"committed":5},"cards":{"yellow":0,"yellowred":0,"red":0},"penalty":{"won":null,"commited":null,"scored":0,"missed":0,"saved":null}},{"team":{"id":85,"name":"Paris Saint Germain","logo":"https:\/\/media-1.api-sports.io\/football\/teams\/85.png"},"league":{"id":65,"name":"Coupe de la Ligue","country":"France","logo":"https:\/\/media-2.api-sports.io\/football\/leagues\/65.png","flag":"https:\/\/media-1.api-sports.io\/flags\/fr.svg","season":2018},"games":{"appearences":2,"lineups":1,"minutes":134,"number":null,"position":"Attacker","rating":null,"captain":false},"substitutes":{"in":1,"out":0,"bench":1},"shots":{"total":null,"on":null},"goals":{"total":1,"conceded":null,"assists":null,"saves":null},"passes":{"total":null,"key":null,"accuracy":null},"tackles":{"total":null,"blocks":null,"interceptions":null},"duels":{"total":null,"won":null},"dribbles":{"attempts":null,"success":null,"past":null},"fouls":{"drawn":null,"committed":null},"cards":{"yellow":1,"yellowred":0,"red":0},"penalty":{"won":null,"commited":null,"scored":null,"missed":null,"saved":null}},{"team":{"id":85,"name":"Paris Saint Germain","logo":"https:\/\/media-2.api-sports.io\/football\/teams\/85.png"},"league":{"id":66,"name":"Coupe de France","country":"France ```
guest

回答2

0

ベストアンサー

@player_name = response["response"][0]["player"]["name"]
ではなく
@player_name = result["response"][0]["player"]["name"]
ではどうでしょうか?

投稿2023/01/14 05:47

asarikz

総合スコア51

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

masakingu

2023/01/15 21:59

ご回答ありがとうございます。 上記のように修正しtrait、 NoMethodError (undefined method `[]' for nil:NilClass のエラーは解決されました。 players/search.html.erbでパーシャルの_player.html.erbの検索結果のレスポンスが表示できません。 よければ、アドアバイス宜しくおねがいします。
asarikz

2023/01/20 05:30

パーシャルの <% if @player.present? %> を <% if @player_name.present? %> に変えるとどうでしょうか?
masakingu

2023/01/26 03:55

ありがとうございます。 上記のようにしたら、解決しました。
guest

0

nil には、[]というメソッドはない!
とおっしゃってますので、
[]の中のデータというより、[]がくっついてる変数がnilなのではないかと。

投稿2023/01/11 03:06

y_waiwai

総合スコア87753

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

masakingu

2023/01/11 22:23

回答ありがとうございます。 理解力なくて申し訳ないのですが、searchアクション内で[]を定義すれば良いでしょうか?
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問