1
0

More than 3 years have passed since last update.

renderメソッドでGoogleMapが消える!? [Rails][Ruby]

Posted at

発生した不具合

renderメソッドを使いエラー文を表示させる実装途中、renderメソッドによるページ遷移後に、導入していたGoogleMapが表示されない事が判明した。

解決方法

結論としては、renderメソッドを使わず、redirect_toメソッドを使用します。

*早めにエラーを解決したかったので、この不具合に関する原因について、この記事では言及しておりません。

変更点

変更前
class CommentsController < ApplicationController
  before_action :authenticate_user!

  def create
    @comment = current_user.comments.build(comment_params)
    if @comment.save
      redirect_to board_path(params[:board_id])
    else
      render template: 'boards/show'
    end
  end


  private
  def comment_params
    params.require(:comment).permit(:text,:board_id).merge(user_id: current_user.id)
  end
end

変更後
class CommentsController < ApplicationController
  before_action :authenticate_user!

  def create
    @comment = current_user.comments.build(comment_params)
    if @comment.save
      redirect_to board_path(params[:board_id])
    else
      # render template: 'boards/show' 消去
      flash[:error_messages] = @comment.errors.full_messages
      redirect_to board_path(params[:board_id])
    end
  end


  private
  def comment_params
    params.require(:comment).permit(:text,:board_id).merge(user_id: current_user.id)
  end
end

以上が主な変更点です。
あとは設定した、<%=flash[:error_messages]%>をこのまま表示させたい部分に挿入して完了です。

メッセージ文をはモデルにて修正しましょう。

まとめ

・render   : controller → view
・redirect_to : controller → URL → route → controller → view

ご覧いただきありがとうございました。
今回のエラーは上記のviewまでにいたるプロセスのどこかで、APIに関する情報が読み込まれない事によるものだと思われます。
発生原因は探している最中ですが、メソッドの基本の流れを理解していたので、すぐに解決できました。

初学者ですので、原因に関することで知見のある方がいましたらぜひコメントお願いします。

1
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
1
0