flash lưu thông báo ngắn cho request tiếp theo — thường dùng sau redirect_to.flash.now lưu cho request hiện tại — dùng khi render (không redirect).
ruby
def create
@post = Post.new(post_params)
if @post.save
flash[:notice] = "Tạo thành công!" # sẽ hiện ở request kế tiếp
redirect_to @post
else
flash.now[:alert] = "Lỗi dữ liệu!" # hiện ngay trong render này
render :new, status: :unprocessable_entity
end
endFlash tự xóa sau khi được đọc — không cần clean up thủ công.
Trong layout, đọc bằng flash[:notice] / flash[:alert].
flash stores a short message for the next request — typically used after redirect_to.flash.now stores it for the current request — used with render (no redirect).
ruby
def create
@post = Post.new(post_params)
if @post.save
flash[:notice] = "Created successfully!" # shown on next request
redirect_to @post
else
flash.now[:alert] = "Data error!" # shown immediately in this render
render :new, status: :unprocessable_entity
end
endFlash is automatically cleared after being read — no manual cleanup needed.
In the layout, read via flash[:notice] / flash[:alert].