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
Rails 5 - Turbolinks 5,Some Js Not Loaded on Page Render
Es6 Template Literals VS. Concatenated Strings
Updating Elements in Rails with Ajax
How to Convert a String to Bytearray
How to Find All Subsets of a Set in JavaScript? (Powerset of Array)
Angular 2 Dependency Injection in Es5 and Es6
The Definitive Best Way to Preload Images Using JavaScript/Jquery
React - Changing an Uncontrolled Input
Merge Keys Array and Values Array into an Object in JavaScript
Overriding Browser's Keyboard Shortcuts
How to Use JavaScript in Ruby on Rails
"Document.Getelementbyclass Is Not a Function"
How to Implement Jquery.Noconflict()
JavaScript with Embedded Ruby: How to Safely Assign a Ruby Value to a JavaScript Variable
Open File Dialog Box in JavaScript
Alternative to Jquery's .Toggle() Method That Supports Eventdata