前提・実現したいこと
投稿アプリを練習で作成しています。
DoubleRenderErrorと出ているので、解決方法を知りたい。
発生している問題・エラーメッセージ
AbstractController::DoubleRenderError in PostsController#create Render and/or redirect were called multiple times in this action. Please note that you may only call render OR redirect, and at most once per action. Also note that neither redirect nor render terminate execution of the action, so if you want to exit an action after redirecting, you need to do something like "redirect_to(...) and return".
該当のソースコード
app/controllers/posts_contoroller.rb
Ruby
1class PostsController < ApplicationController 2 before_action :set_post, only: %i[ show edit update destroy ] 3 4 # GET /posts or /posts.json 5 def index 6 @posts = Post.all 7 end 8 9 # GET /posts/1 or /posts/1.json 10 def show 11 end 12 13 # GET /posts/new 14 def new 15 @post = Post.new 16 end 17 18 # GET /posts/1/edit 19 def edit 20 end 21 22 # POST /posts or /posts.json 23 def create 24 @post = Post.new(post_params) 25 26 if @post.save 27 redirect_to @post, notice: '投稿が作成されました。' 28 else 29 render :new 30 end 31 32 respond_to do |format| 33 if @post.save 34 format.html { redirect_to @post, notice: "Post was successfully created." } 35 format.json { render :show, status: :created, location: @post } 36 else 37 format.html { render :new, status: :unprocessable_entity } 38 format.json { render json: @post.errors, status: :unprocessable_entity } 39 end 40 end 41 end 42 43 # PATCH/PUT /posts/1 or /posts/1.json 44 def update 45 respond_to do |format| 46 if @post.update(post_params) 47 format.html { redirect_to @post, notice: "Post was successfully updated." } 48 49 format.json { render :show, status: :ok, location: @post } 50 else 51 format.html { render :edit, status: :unprocessable_entity } 52 format.json { render json: @post.errors, status: :unprocessable_entity } 53 end 54 end 55 end 56 57 # DELETE /posts/1 or /posts/1.json 58 def destroy 59 @post.destroy 60 respond_to do |format| 61 format.html { redirect_to posts_url, notice: "Post was successfully destroyed." } 62 format.json { head :no_content } 63 end 64 end 65 66 private 67 # Use callbacks to share common setup or constraints between actions. 68 def set_post 69 @post = Post.find(params[:id]) 70 end 71 72 # Only allow a list of trusted parameters through. 73 def post_params 74 params.require(:post).permit(:title, :body) 75 end 76end
試したこと
ここに問題に対して試したことを記載してください。
redirect_to ,, and returnを記載してみたがエラー解決できず
補足情報(FW/ツールのバージョンなど)
pc: MacbookAir
rails: 5.2.6
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2021/11/03 11:43