In a Rails controller, when do you use flash.now instead of flash, and what do flash.keep and add_flash_types add?
answer
- next request versus this request
- redirect pairs with flash
- render pairs with flash.now
- keep survives one more hop
- add_flash_types :warning adds a redirect_to option
basics
~20 sflash[:notice] is shown on the next request, so it pairs with redirect_to; flash.now[:alert] is shown only in the current request, so it pairs with render. flash.keep carries entries through one more request, and add_flash_types adds keys usable like notice: and alert:.
solid answer
~40 sThe flash lives in the session under `"flash"`. When a request reads it, every loaded entry is marked for discard at the end of that request; an entry you assign with `flash[:notice] =` is unmarked, so it survives into the **next** request, the one a `redirect_to` triggers. `flash.now[:alert] =` assigns and marks the entry for discard straight away, so it appears in the current render and nowhere else. `flash.keep` (or `flash.keep(:notice)`) unmarks loaded entries so they survive one more request, useful across a second redirect; `flash.discard` does the opposite. `add_flash_types :warning` in a controller lets `redirect_to ..., warning: "..."` set `flash[:warning]` and defines a `warning` helper for views, as Rails does for `:notice` and `:alert`.
code
ruby · 15 linesclass ApplicationController < ActionController::Base
add_flash_types :warning
end
class PickupSlotsController < ApplicationController
def update
slot = PickupSlot.find(params.expect(:id))
if slot.update(slot_params)
redirect_to slot, warning: "Customers on this slot will be emailed.", status: :see_other
else
flash.now[:alert] = "Slot could not be moved."
render :edit, status: :unprocessable_content
end
end
endgo deeper
Recall the pairing: flash with redirect_to for the next page, flash.now with render for the current one, plus notice: and alert: on redirect_to.
Explain the discard set, why flash before render repeats and flash.now before redirect vanishes, what keep and discard change, and what add_flash_types defines.
Show you diagnose flashes that appear late from requests that never read the flash, double redirects that need keep, and resets that wipe the message.
Standardise flash types and a single layout partial so every controller signals outcomes the same way, and keep messages short in a cookie-backed session.
## Where the flash lives The flash is a **hash stored in the session** under the key `"flash"`, with one twist: entries are swept automatically. Action Dispatch tracks a **discard set**: 1. When a request first touches `flash`, Rails loads the stored entries and marks **all** of them for discard at the end of this request. 2. Assigning `flash[:notice] = "..."` stores the entry and **removes** it from the discard set, so it is written back to the session. 3. At the end of the request Rails writes back only the entries not marked for discard. That is the whole mechanism behind "available in the next request and then gone". ## flash versus flash.now In a bakery pre-order app, placing an order redirects, while choosing a full pick-up slot re-renders the form: ```ruby def create @order = current_basket.orders.build(order_params) if @order.save redirect_to @order, notice: "Pre-order placed.", status: :see_other else flash.now[:alert] = "That pick-up slot is full." render :new, status: :unprocessable_content end end ``` - **`flash[:notice]`** (or `redirect_to ..., notice:`) survives into the **next** request, which is the GET that follows the redirect. The `show` page's layout displays it, then it is swept. - **`flash.now[:alert]`** assigns the entry **and** marks it for discard immediately. The current render can read `flash[:alert]`, and nothing is carried forward. ## The two classic bugs | Mistake | Symptom | |---|---| | `flash[:alert]` before `render` | the message shows now **and again** on the next page the user opens | | `flash.now[:notice]` before `redirect_to` | the message never appears, because it was discarded before the redirected request | The rule of thumb: **`flash` with `redirect_to`, `flash.now` with `render`.** ## flash.keep and flash.discard - **`flash.keep`** removes all loaded entries from the discard set; `flash.keep(:notice)` keeps one. Use it when an action that received a flash immediately redirects again, for example a legacy `/preorders` URL that forwards to `/orders`: without `keep`, the message is swept at the first hop. - **`flash.discard`** (or `flash.discard(:notice)`) marks entries to be dropped at the end of the current request, for a message you want to show now but not again. One more detail follows from the mechanism: entries are swept by the next request that **reads** the flash. A request that never touches `flash`, such as a JSON endpoint that does not load the layout, leaves them in the session for the next page that does. ## notice, alert and add_flash_types `ActionController::Flash` registers `:notice` and `:alert` as **flash types**. Each type gives you: - a `redirect_to` option: `redirect_to @order, notice: "Saved."`; - a private controller method and a view helper that returns `flash[type]`: `<%= notice %>`. `add_flash_types :warning, :success` in `ApplicationController` adds more. Without it, a custom key still works through the general option: `redirect_to @order, flash: { warning: "Pick-up moved." }`. ## Checking it in a test An integration test can assert the flash on both sides of a redirect: ```ruby post orders_url, params: { order: { pickup_slot_id: slots(:saturday).id } } assert_equal "Pre-order placed.", flash[:notice] follow_redirect! assert_select ".flash-notice", "Pre-order placed." ``` The first assertion reads the flash the action set; the second proves the next request actually displayed it. For a `flash.now` message, assert on the rendered body of the same response, since nothing is carried forward. ## Showing it in the layout The layout usually loops over the flash so every page displays whatever arrived: ```erb <% flash.each do |type, message| %> <div class="flash flash-<%= type %>"><%= message %></div> <% end %> ``` Because entries are swept automatically, nothing has to delete them after display. ## Interactions worth knowing - **`reset_session`** also clears the flash. Set the message **after** resetting, or it is lost. - **The flash is part of the session**, so with the cookie store its text counts toward the 4 KB cookie limit; keep messages short.
- Why does a message set with flash[:alert] before render show up twice?The current render reads `flash[:alert]` and displays it. Because it was assigned with plain `flash`, it is not marked for discard, so it is written to the session and shown again by the next request that reads the flash. `flash.now[:alert]` marks it for discard at once and avoids the repeat.
- What does add_flash_types :warning define?It registers `:warning` in the controller's flash types, so `redirect_to path, warning: "..."` copies the value into `flash[:warning]`, and it defines a private `warning` method that returns `request.flash[:warning]`, exposed to views with `helper_method`. Subclasses inherit the type.
The flash is a note left on the counter for the next shift: whoever next reads the counter acts on it and bins it at the end of their shift. flash.now is a note shown to the customer in front of you and binned at once; flash.keep is writing 'pass this on' across it.
- flash.now[:notice] before redirect_to shows the message on the next page
- flash entries are deleted after the next request even if it never reads them
- a custom key needs add_flash_types before flash[:key] can be set at all
- flash.keep makes a message permanent until it is deleted by hand
- reset_session leaves flash messages in place for the next request