Search code examples
htmlruby-on-railsformssearchransack

Rails radio_buttons multiple selection for same attribute, is it possible?


I have a search_form_for and I need to be able to select multiple Payment statuses to make a Ransack search.

We already have an f.select dropdown box for this attribute, but we now need to be able to select more than one status at the same time.

form:

<%= search_form_for @search, url: admin_payments_path, html: {class: "form-inline"} do |f| %>
  <div class="form-group">
    <%= f.select :status_eq, payment_status_selector, { include_blank: "Payment status.."}, class: "form-control gray" %>
  </div>  
<% end %>
  

I've tried:

<%= f.select :status_eq, payment_status_selector, {include_blank: false}, {multiple: true, as: :radio_buttons}  %>

gives me a select box with all the options allowing me to select multiple, but they are not radio_buttons and an empty value "" is passed along with the selected options.

    <% payment_status_selector.each do |status| %>
      <%= radio_button_tag :status_eq, "#{status[1]}", false,  class: 'radio-checkbox' %>
      <%= label_tag( "#{status[0]}") %>
    <% end %>

This gives me a radio_button for each possible status, but I can't select more than one.

I can't figure out the correct way to do it. Maybe with check_boxes are a better option to be able to select/unselect statuses?


Solution

  • Yes, using check_box will be a better option.

    Try,

    <% payment_status_selector.each do |status| %>
      <%= f.check_box :payment_statuses, { multiple: true }, status, false %>
      <%= label status %>
    <% end %>
    

    And you can expect the values in controller from params as:

    { search: { payment_statuses: ["status 1", "status 2"] }

    make sure that payment_status_selector returns array of values.

    Hope that helped.

    Reference: https://medium.com/programming-problem-solving-logbook/rails-multiple-checkboxes-e9c4c7fda356