・ Ruby: 2.5.7 Rails: 5.2.4 ・ Vagrant: 2.2.7 -VirtualBox: 6.1 ・ OS: macOS Catalina
Gemfile
gem 'jquery-rails'
Terminal
bundle install
controller
def create
@book = Book.new(book_params)
@book.user_id = current_user.id
if @book.save
redirect_to book_path(@book)
flash[:notice] = "The book was posted"
else
@books = Book.all
flash.now[:alart_flash] = "Book posting failed"
render 'index'
end
end
When the book is posted, it is named notice, and when it fails, it is named alart_flash. You can change the name here by yourself! When set to flash [:], the next action is displayed. If you set it to flash.now [:], it will disappear when you move to the next action. Note that render is not an action as it only calls the specified views. Note that redirect_to will be the next action, so it will not be displayed if it is flash.now.
application.scss
.flash{
width: 100%;
height: 30px;
font-size: 18px;
text-align: center;
padding: 0;
z-index: 1;
}
.notice{
background-color: #65A2FF;
}
.alart_flash{
color: #FFFFFF;
background-color: #FF0000;
}
application.js
//Flash message
$(function(){
$('.flash').fadeOut(4000); //Disappears over 4 seconds
});
Recommended Posts