Rendering with a flash message
現在建立一個 flash 錯誤訊息提示:
app/controllers/sessions_controller.rb
def create
user = User.find_by(email: params[:session][:email].downcase)
if user && user.authenticate(params[:session][:password])
# Log the user in and redirect to the user's show page.
else
flash[:danger] = 'Invalid email/password combination' # Not quite right!
render 'new'
end
end
因為之前在 application.html.erb 已經有 flash 的 layout:
<body>
<%= render 'layouts/header' %>
<div class="container">
<% flash.each do |message_type, message| %>
<div class="alert alert-<%= message_type %>"><%= message %></div>
<% end %>
<%= yield %>
<%= render 'layouts/footer' %>
<%= debug(params) if Rails.env.development? %>
</div>
.
.
.
</body>
所以當登入失敗會出現錯誤訊息:

不過 flash 的持續性是在一個請求內持續存在,但 render 不算一個新的請求,所以如果這時候你瀏覽其他頁面,例如首頁,會發現這個錯誤訊息還在:
