LoginSignup
0
0

More than 3 years have passed since last update.

ストロングパラメータはtrueなのになぜかテーブルに保存できない。

Posted at

うまくいかなかったこと

paramsに値は入っているのに、テーブルに保存ができない。エラーも出ない。

ターミナル
     6: def create
     7:   judge = Judge.new(judge_params)
     8:   judge.save
 =>  9:   binding.pry
    10: 
    11:   redirect_to  root_path 
    12: end

[1] pry(#<JudgesController>)> judge
=> #<Judge:0x00007fd58efb37c0
 id: nil,
 judge_correct_id: 2,
 comment: "めお",
 created_at: nil,
 updated_at: nil>
[2] pry(#<JudgesController>)> judge.save
=> false

結論

アソシエーションを組んで外部キーが存在するはずなのに、それをmigrationファイルに記入していなかったから。

検証方法(save!メソッド)

saveメソッドはtrueかfalseしか返しませんが、save!メソッドはfalseの場合、例外が発生するそうなので、ターミナルにエラーの原因となっていることが表示されました。
ターミナル上でインスタンス変数.saveとしてfalseと返されたところをインスタンス変数.save!としたところ、

Validation failed: User must exist, Post must exist・・・hogehoge

という記述がありました。
確かにアソシエーションを組んでいるのにUserとPostに関係するidを作成していなかったなと思い、追加したところうまく行きました。

以上

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0