If you set form state explicitly it will be lost at validation stage

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the rails category.

Last Updated: 2024-07-26

I had the following code:

<%= form_with(model: @tutor_search_form) %>
  <div class="layout__one_of_two_columns">
  <%= f.label "Online" %>
  <%= f.check_box :online_available, checked: true %>
  ...
<% end %>

I wanted the params (e.g. whether online_available was checked or not) to be preserved after failed validations or when revisiting the search with a search again button.

Unfortunately, no matter what, the box remained checked...

The issue was that the check_box did not update its checked status based on the @tutor_search_form state; it was fixed to true. Therefore the parameters weren't preserved when revisiting the search. I fixed this by removing the checked: true bit and instead achieving the desired effect setting the default of online_available to be true when initializing @tutor_search_form in the controller and then letting the data percolate down.