Search code examples
ruby-on-railsformssessionbackbreadcrumbs

Ruby on Rails Link to Previous Page on Form Failing After Invalid Input


I have a form page in my app, and I'm trying to add breadcrumbs to it. The form can be accessed from two separate pages, so instead of having traditional breadcrumbs, I want to put a single breadcrumb with the word "back" that links to the page the user comes from. I can get this to work using the following code:

<%= content_for :breadcrumbs do %>
<%= breadcrumb t(".back"), :back %>
<%= breadcrumb t(".add_org") %>
<% end %>

However, if the form is passed an invalid input, the "back" link redirects to the form page, because the session has changed, as opposed to the page the user visited before. Is there any way to always redirect the user back to the previous page even after invalid input or a refresh?


Solution

  • you could set a hidden_field on your form to cache url_for(:back) on the first time (that is the previous link before the form page), as below:

    <%= breadcrumb t(".back"), params.dig(:bread,:back_url) || url_for(:back) %>
    
    <%= form_with(model: bread, local: true) do |form| %>
      <%= form.hidden_field :back_url, value: params.dig(:bread,:back_url) || url_for(:back)  %>
      # the rest of form ...
    <% end %>