Search code examples
ruby-on-railsruby-on-rails-3ruby-on-rails-3.2ransack

Preserve State of Pushed Radio Buttons


How would one go about preserving the state of a "pushed" radio button after running a search? I'm using the Ransack gem to generate this search.

View:

<%= search_form_for @search do |f| %>

  <strong>Location</strong></br>

  <%= radio_button_tag("q[location_cont]", "Kentucky") %>
  <%= label_tag "Kentucky" %></br></br>

  <%= radio_button_tag("q[location_cont]", "Kansas") %>
  <%= label_tag "Kansas" %></br></br>

  <%= f.submit "Search" %>
<% end %>

Controller:

def index
  @search = Job.search(params[:q])
  @jobs = @search.result
end

Solution

  • If you were using form_tag, then radio_button_tag would be a valid field type to use. And you could use the third parameter to indicate if the button is selected or not:

    <%= radio_button_tag("q[location_cont]", "Kentucky", params[:q] && params[:q][:location_cont] == "Kentucky") %>
    <%= label_tag "Kentucky" %></br></br>
    
    <%= radio_button_tag("q[location_cont]", "Kansas", params[:q] && params[:q][:location_cont] == "Kansas") %>
    <%= label_tag "Kansas" %></br></br>
    

    Since you are using the Ransack search_form_for, then you want to use radio_button and I think you'd want something like this:

    <%= f.radio_button(:location_cont, "Kentucky") %>
    <%= f.label :location_cont, "Kentucky", value: "Kentucky" %></br></br>
    
    <%= f.radio_button(:location_cont, "Kansas") %>
    <%= f.label :location_cont, "Kansas", value: "Kansas" %></br></br>