LoginSignup
0
0

More than 3 years have passed since last update.

binding.pryを使用したエラー解決例

Last updated at Posted at 2021-03-05

①controllerでbinding.pryを設定します。

def create
    binding.pry
    comment = Comment.create(comment_params)
    redirect_to "/items/#{comment.item_id}"
  end

②ターミナルでcreateを確認すると、ROLLBACKが表示されています。

[3] pry(#<CommentsController>)> comment = Comment.create(comment_params)
   (0.2ms)  BEGIN
  ↳ (pry):3:in `create'
  User Load (0.5ms)  SELECT `users`.* FROM `users` WHERE `users`.`id` = 11 LIMIT 1
  ↳ (pry):3:in `create'
   (0.1ms)  ROLLBACK
  ↳ (pry):3:in `create'
=> #<Comment:0x00007fe2f9494f38 id: nil, user_id: 11, item_id: 24, text: "a", created_at: nil, updated_at: nil>

③comment.errors.full_messages こちらの記述でエラーメッセージを取得します。

[4] pry(#<CommentsController>)> comment.errors.full_messages
=> ["Tweet must exist"]

④バリデーションのエラーなのでmodels/comment.rbを確認します。

class Comment < ApplicationRecord
  belongs_to :tweet
  belongs_to :user
end

⑤アソシエーションをitemに変更して修正完了です。

class Comment < ApplicationRecord
  belongs_to :item
  belongs_to :user
end
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