ActiveRecord + Turbo Streams: Persisting Pagination State Across Reflex Calls
0 reputation · 07 Jun 2025, 23:44 UTC
0 reputation · 07 Jun 2025, 23:44 UTC
We want to display a large list of records in a Rails view using Reflex to update the list via Turbo Streams, while limiting the number of records per page and preserving the current page across multiple Reflex invocations.
Reflex actions are stateless between requests; ActiveRecord scopes can bound a query with limit and offset, but the client does not automatically remember the page number when a Turbo Stream replaces the list. Without explicit state handling, the next “next page” click may reset to page 0 or produce inconsistent results.
The community has not agreed on a standard pattern for persisting pagination parameters across Reflex calls. Options include storing the page number in the session, embedding it in a hidden field, or passing it as a parameter on every Reflex event. Each approach has trade‑offs in security, UX, and complexity.
1. What is the most secure way to transmit the current page number in a Reflex request without exposing it to tampering?
2. Should the page state be stored server‑side (e.g., session) or client‑side (e.g., hidden field) to maintain consistency?
3. How can we validate and sanitize pagination parameters to prevent injection or out‑of‑range errors?
31775 reputation · 08 Jun 2025, 06:02 UTC
def current_page
page = cookies.signed[:page]
page = page.to_i > 0 ? page.to_i : 1
page = 1 if page > max_pages
page
end
@records = Record.page(current_page).per(20)
def next_page
cookies.signed[:page] = current_page + 1
@records = Record.page(cookies.signed[:page]).per(20)
# Turbo Stream rendering happens automatically
end
turbo_stream.replace "records_list", partial: "records/list", locals: { records: @records }
rescue ActiveSupport::MessageVerifier::InvalidSignature
cookies.signed[:page] = 1
@records = Record.page(1).per(20)
end
Do you currently use a signed cookie or a session to store user data? Knowing this will help tailor the exact code snippets for your setup.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.