Best Way to Display Flash Notices in Rails

Best practice method of displaying flash messages

I'm doing it this way:

<% flash.each do |key, value| %>
<%= content_tag :div, value, class: "flash #{key}" %>
<% end %>

How to display flash messages in rails service object

The flash method is only available in the controller. When you want to set the flash in the service object then you need to pass the flash to the service object.

# in the controller
def create
@user_stock = UserStocksCreator.new(current_user, params, flash).call
redirect_to my_portfolio_path
end

# in the service
class UserStocksCreator
def initialize(current_user, params, flash)
@current_user = current_user
@params = params[:stock_ticker]
@flash = flash
end

def call
# unchanged...
end

private

attr_accessor :current_user, :params, :flash
end

Display flash alert from controller's concern

AJP's answer solved my issue.

TLDR: use flash[:danger] with redirect_to

How to display a Rails flash notice upon redirect?

Remove the .now. So just write:

flash[:notice] = 'Successfully checked in'
redirect_to check_in_path

The .now is specifically supposed to be used when you are just rendering and not redirecting. When redirecting, the .now is not to be used.

Rails flash notice in current view, before redirect

So, this is clearly a workaround to the problem. But I achieved it with unhiding a div or just flashing a JS alert with the notice message on the form submit:

<%= f.submit 'Run Job', :onclick => "return showNotice()"%>

Display flash message on user update

I got it. I needed to use the flash.keep method to carry the flash into the next request.

def show
flash.keep
end

Thanks to Pavan and Baldrick



Related Topics



Leave a reply



Submit