In a Rails form flow, when does a problem go in the model's errors rather than the flash, and why use flash.now before render?
answer
- errors: per attribute, this request
- flash: one message, next request
- redirect_to ..., notice:
- flash.now[:alert] before render
- session cookie caps at 4096 bytes
basics
~20 sInput problems belong in the model's errors, shown by the re-rendered form; the flash carries a short message across a redirect, like a success notice. For a banner on a re-render use flash.now, or it repeats on the next page.
solid answer
~40 s`@volunteer.errors` is tied to attributes and exists only on the object in this request, which is exactly what a 422 re-render of the form needs: messages beside fields and in a summary. The flash lives in the session and is meant for the next request, so it fits `redirect_to @volunteer, notice: "Thanks for signing up."` after a success, or an `alert:` when there is no form to re-render, such as a closed event. If a failed save should also show a banner, set `flash.now[:alert]` before `render`: plain `flash[:alert] =` is readable in this render and is kept for the next request too, so the banner shows twice. Copying validation messages into the flash and redirecting loses the field association and the typed input, and the session cookie holds at most 4096 bytes.
code
erb · 6 lines<%# app/views/layouts/application.html.erb (excerpt) %>
<% flash.each do |type, message| %>
<div class="flash flash-<%= type %>" role="status"><%= message %></div>
<% end %>
<%= yield %>go deeper
Recall that validation errors show in the re-rendered form, while the flash carries a short message such as a success notice across a redirect.
Explain the lifetimes: errors die with the request, flash survives one redirect, and flash.now limits a message to the current render.
Catch the double-banner bug from flash before render, keep validation messages out of the flash, and route non-field failures to :base or a redirect deliberately.
Define one messaging contract for the app, what goes in errors, flash notices and alerts, so controllers, layouts and Turbo responses stay consistent.
## Two channels with different lifetimes | | `record.errors` | `flash` | |---|---|---| | Attached to | one model object | the user's session | | Lifetime | the current request | this request and the next one (`flash.now`: this request only) | | Granularity | per attribute, plus `:base` | a key such as `:notice` or `:alert` | | Shown by | the form's summary and per-field messages | the layout's banner area | | Survives a redirect | no | yes, that is its purpose | The flash itself is the sessions leaf's subject; what matters here is which channel a form outcome belongs in. ## Use errors for anything about the input A blank name, a malformed email or a duplicate sign-up is a fact about the submitted data. Put it on the model, through validations or `errors.add`, and re-render the form with status `:unprocessable_content`. The user sees which field is wrong, the values they typed, and the summary. Problems that concern the whole submission rather than one field go on `:base`, still inside the form. ## Use the flash for outcomes that leave the form - **Success.** `redirect_to @volunteer, notice: "Thanks for signing up."` sets `flash[:notice]` for the page after the redirect. - **Failures with nothing to re-render.** The event closed while the user was typing, or they lack permission: `redirect_to events_path, alert: "Sign-ups for this event are closed."` - **Banners on top of a re-render.** Optional, and only with `flash.now`. ## Why flash.now before render Assigning `flash[:alert] = "..."` stores the message and marks it to be kept for the next request, while also making it readable right away. With `render` there is no next request in the flow, so: 1. The re-rendered form shows the alert, because the layout reads `flash[:alert]`. 2. The user fixes the form and submits; the success redirect lands on the next page. 3. That page shows the stale alert again, next to the success notice. `flash.now[:alert] = "..."` makes the message available only to the current render and discards it at the end of the request, which is exactly what a re-render needs. ## Why not move validation messages into the flash - **Field association is lost.** The flash holds simple values such as strings, not error objects, so the form cannot mark or describe individual fields. - **The input is lost.** Redirecting means a fresh object and a blank form. - **Size.** With the default cookie session store, everything in the session must fit in a 4096-byte cookie; a long list of messages can raise `ActionDispatch::Cookies::CookieOverflow`. - **Status.** A redirect cannot carry the 422 that tells Turbo Drive, tests and logs that the submission failed. ## With Turbo in the picture A 422 response to a Turbo Drive form submission replaces the page body, layout included, so a `flash.now` banner rendered by the layout appears as expected. When the form lives inside a Turbo Frame, only the frame's content is replaced; a banner printed by the layout outside the frame does not update, so the message has to be rendered inside the frame or delivered another way, such as a Turbo Stream (that mechanism belongs to the Turbo leaves). ## A combined example ```ruby def create @volunteer = Volunteer.new(volunteer_params) if @volunteer.save redirect_to @volunteer, notice: "Thanks for signing up." else flash.now[:alert] = "Please fix the highlighted fields." render :new, status: :unprocessable_content end end ``` ## Interview summary Errors describe the input and travel with the object into a re-render; the flash describes an outcome and travels across a redirect. When a re-render also needs a banner, use `flash.now`, because a plain flash assignment outlives the response it was meant for.
- What happens if a failed save sets flash.now[:alert] and then redirects?The message is discarded at the end of the current request, and the redirect starts a new one, so the alert never appears. `flash.now` is for `render`; use `flash[:alert]` or the `alert:` option with `redirect_to`.
- Where should a 'sign-ups are closed' check report its failure?If it is discovered while validating the submission, add it to `errors` on `:base` and re-render with 422 so the user sees it in the form. If the page itself should no longer be reachable, redirect away with an `alert:` flash.
- flash[:alert] set before render shows only on the next page, never on this one.
- Validation messages should be copied into the flash so they survive a redirect.
- flash.now keeps the message for the next request as well as the current one.
- Model errors are stored in the session, so a redirect keeps them.
- The notice: option works on render the same way it works on redirect_to.