0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[Rails]ダブルレンダリングと言われる

Posted at

下記のエラーが出て解決に小一時間かかったので共有します。

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".

コントローラーの中でredirect_toを用いてレンダリングしようと思ったら起こりました。

class HomeController < ApplicationController
  def top
    @posts = Post.all.order(created_at: :desc)
    byebug
    @map = Map.all         
    @arr=[]                
    @map.each do |m|        
      @arr.push({lat: m.latitude, lng: m.longitude })
    if user_signed_in?
      #こいつでダブルレンダリングと言われる
      redirect_to posts_path and return
    end
    end
  end

他にリダイレクト処理していないのになんでー

結論

each文の中に入れ子になっていたため。

each do |m| 〜 end の〜部分はブロック引数です。
引数の中でレンダリング処理が行われ、httpレスポンスを受け取り、
webサーバーに対して受け取ったURIを要求する。
しかし当のwebサーバーはeach処理の結果も返しつつ、レンダリング結果も返さなくならなきゃいけなくなった為エラーが起こったのでしょう。

▼参考
Rails Guide -ダブルレンダリングエラーの回避-
修正方法 'このアクションでレンダリングおよび/またはリダイレクトが複数回呼び出されました'

Deviseコントローラーで似たエラーが出る場合は

こちらの記事にあるようにdeviseコントローラー内では遷移処理にredirect_toを使わなくて言いそうです。
https://qiita.com/yo_instead_what/items/582cc071b3e0a8a2b583

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?