気ままに気ままのエンジニアブログ

定期的に得た知見を気ままに発信中

【Rails/enum】ArgumentError ('0' is not a valid section):エラーの解決方法

こんにちは。

気がついたら記念すべき50投稿目の記事でした。
誰かのソリューションになってれば嬉しい!そんなことを思った寒い日の夜。

どうもハチマキです。

はじめに

今回は、formでselectできるようにするため、enumを定義しました。
その際に発生したArgumentError ('0' is not a valid section):のエラー解決方法ついて書いていきたいと思います。

では早速行きましょう!

本日の概要 : ArgumentError ('0' is not a valid section):エラーの解決方法

事前情報

今回はこのようなテーブルを使っていきます。

create_table "schedule_results", force: :cascade do |t|
    t.datetime "match_date_time"
    t.integer "section"
    t.integer "opponent"
    t.integer "match_result"
    t.integer "stadium"
    t.integer "home_and_away"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

事象

対象のカラムをintegerにして、準備万端!いざformを投稿したらArgumentError ('0' is not a valid section):エラーが発生・・

エラー例

ターミナル

ArgumentError ('0' is not a valid section):
  
app/controllers/match/schedule_results_controller.rb:11:in `create'
Started POST "/match/schedule_results" for 127.0.0.1 at 2020-10-27 20:29:08 +0900
Processing by Match::ScheduleResultsController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"69buIqkOJunb1OBSSv9CSaePvK5EnZmxLJ6JVpY1THE3hiqB/j/KPYxiPK51/kZcaCT2IZJ6xQ2YN87oZZgsVQ==", "schedule_result"=>{"match_date_time"=>"2020-10-28", "section"=>"0", "opponent"=>"1", "match_result"=>"", "stadium"=>"0", "home_and_away"=>"0"}, "commit"=>"スケジュールを投稿する"}
Completed 500 Internal Server Error in 2ms (ActiveRecord: 0.0ms)

原因予測

ArgumentError。。。
つまり、引数が正しくない時や足りない時に発生するエラーなので、返ってきた値のどこかに問題がありそうやなぁ🤔

原因

結論!こいつです。

{"match_date_time"=>"2020-10-28", "section"=>"0", "opponent"=>"1", "match_result"=>"", "stadium"=>"0", "home_and_away"=>"0"}, "commit"=>"スケジュールを投稿する"}

整数で返ってきてるのに!と思ったら'' "(ダブルクォーテーション)で囲われており、文字列で返ってきていたことが原因でエラーが発生してました。(デフォルトで" "で囲われてるみたいです)

解決方法

formでenumを定義してる箇所に「.keys」を定義してあげることでint型としてカラムに保存され、解決に至りました。

new.htm.haml

%div.form-group
    = f.label :section, ''
    = f.select :section, ScheduleResult.sections.keys, class: 'form-control'
%div.form-group
    = f.label :opponent, '対戦チーム'
    = f.select :opponent, ScheduleResult.opponents.keys, class: 'form-control'

= f.submit '登録する', class: 'btn btn-info btn-block'

ターミナル

Started POST "/match/schedule_results" for 127.0.0.1 at 2020-10-27 20:29:15 +0900
Processing by Match::ScheduleResultsController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"kZ/htn7HyKQ0ttR/dNd0NSxtUGdQyGuXkc3pt6XSbxkj/sxCllMi4012QbZwMXd+s76fIy42FfCeSBo4J8fLNg==", "schedule_result"=>{"match_date_time"=>"2020-10-29", "section"=>"第1節", "opponent"=>"リューレント", "match_result"=>"", "stadium"=>"古々崎第1G", "home_and_away"=>"ホーム"}, "commit"=>"スケジュールを投稿する"}
   (0.1ms)  begin transaction
  ↳ app/controllers/match/schedule_results_controller.rb:11
  ScheduleResult Create (0.8ms)  INSERT INTO "schedule_results" ("match_date_time", "section", "opponent", "stadium", "home_and_away", "created_at", "updated_at") VALUES (?, ?, ?, ?, ?, ?, ?)  [["match_date_time", "2020-10-29 00:00:00"], ["section", 0], ["opponent", 0], ["stadium", 0], ["home_and_away", 0], ["created_at", "2020-10-27 11:29:15.309864"], ["updated_at", "2020-10-27 11:29:15.309864"]]
  ↳ app/controllers/match/schedule_results_controller.rb:11
   (2.8ms)  commit transaction
  ↳ app/controllers/match/schedule_results_controller.rb:11
   (0.1ms)  begin transaction
  ↳ app/controllers/match/schedule_results_controller.rb:12
   (0.1ms)  commit transaction
  ↳ app/controllers/match/schedule_results_controller.rb:12
Redirected to http://0.0.0.0:3000/match/schedule_results/new
Completed 302 Found in 9ms (ActiveRecord: 3.9ms)

int型でDBに保存されました!解決解決っと。

補足

文字列でカラムに保存することも可能ですが、あまりよろしくないみたいです。
▽ご参考までにコード例

Started POST "/match/schedule_results" for 127.0.0.1 at 2020-10-28 08:01:57 +0900
Processing by Match::ScheduleResultsController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"LBP7lJ0k3LiS2123eLG7rfIE6CY5ORoaROaX8q7o6M/wQz83yhUwbMVtgUtHsL+4Pa+iqe/eRqbwT9BMXUWI6w==", "schedule_result"=>{"match_date_time"=>"2020-10-14", "section"=>"第1節", "opponent"=>"", "match_result"=>"", "stadium"=>"古々崎第1G", "home_and_away"=>"ホーム"}, "commit"=>"スケジュールを投稿する"}
   (0.1ms)  begin transaction
  ↳ app/controllers/match/schedule_results_controller.rb:11
  ScheduleResult Create (1.1ms)  INSERT INTO "schedule_results" ("match_date_time", "section", "opponent", "stadium", "home_and_away", "created_at", "updated_at") VALUES (?, ?, ?, ?, ?, ?, ?)  [["match_date_time", "2020-10-14 00:00:00"], ["section", "第1節"], ["opponent", ""], ["stadium", "古々崎第1G"], ["home_and_away", "ホーム"], ["created_at", "2020-10-27 23:01:57.699941"], ["updated_at", "2020-10-27 23:01:57.699941"]]
  ↳ app/controllers/match/schedule_results_controller.rb:11
   (4.0ms)  commit transaction
  ↳ app/controllers/match/schedule_results_controller.rb:11
   (0.1ms)  begin transaction
  ↳ app/controllers/match/schedule_results_controller.rb:12
   (0.0ms)  commit transaction
  ↳ app/controllers/match/schedule_results_controller.rb:12
Redirected to http://0.0.0.0:3000/match/schedule_results/new
Completed 302 Found in 12ms (ActiveRecord: 5.3ms)