Hitsuji_monのブログ~ 村上春樹のあれ ~

文学好きな組み込み系エンジニア

Rails 日記App制作 ~Rails5.2以上でのredirect_backの使い方 | Git~

コメント機能にバリデーションつけたら

redirect_to :back
# Undefined method エラー

・Rails5.2以上からは, redirectの書き方が変わって、上記は認識されなくなったらしい

redirectの書式 [Rails5.2以上]

qiita.com

#旧redirect
redirect_to :back

#現行redirect
redirect_back(fallback_location: root_path)

で目的だったコメントModelに対するバリデーション機能の書き方

#古い書き方: エラー
# app/controllers/comments_controller.rb
       ~
        redirect_to :back, flash: {
            comment: comment,
            error_messages: comment.errors.full_messages
        }
      ~
#現在の書き方
# app/controllers/comments_controller.rb
       ~
      #posts_pathが今回のroot
       redirect_back fallback_location: posts_path, flash: {       
          comment: comment,
          error_messages: comment.errors.full_messages
      }
      ~

'削除'アクションとともに、データベース内のデータも削除するように関連づける
■アソシエーションのオプション
ここまでに Post モデルや Comment モデルに has_many のアソシエーションを設定してきたが、
現状の設定だと投稿記事やコメントを削除した時、関連するテーブルやデータが残ったままになってしまう。

そんな時は、アソシエーションの 「dependent」オプションを使用する。

dependent オプションを設定しておくと関連するテーブルデータを一緒に削除してくれるらしい。