Home > Back-end >  How to get an array of values from a group of checkbox in Ruby on Rails?
How to get an array of values from a group of checkbox in Ruby on Rails?

Time:04-11

I'm new to Rails and I don't understand how to solve this problem.

I've got 2 entities: Player and Call Up; N:M relationship. So basically a call up has an id, some attributes (like opponents, date...) and a list of players.

In the new call up's form i added a table of players that could be included. Each row has checkbox with the corresponding player id. Here's the view:

<%= form_with(model: call_up) do |form| %>
<!--Call Up Informations-->
<!---->
  <table >
    <thead>
      <tr>
        <th colspan="5"></th>
      </tr>
    </thead>
    <tbody>
      <% @players.each do |player| %>
        <tr>
          <td><%=player.first_name %></td>
          <td><%=player.last_name %></td>
          <td><%=player.number %></td>
          <td><%=player.role %></td>
          <div >
            <td><%=form.check_box :player_ids, class: "form-check-input", value: player.id %></td>
          </div>
        </tr>
      <% end %>
    </tbody>
  </table>

  <br>

  <div >
    <%= form.submit "Create Call Up", class: "btn btn-dark" %>
  </div>
<% end %>

In the controller i tried to get the player ids array by using params[:player_ids] but it produce a nil error. Can anyone help me out?

CodePudding user response:

Sometime digging the source code help us a lot, especially when the guide is not clear. Take a look at all check_box params

def check_box(object_name, method, options = {}, checked_value = "1", unchecked_value = "0")
  Tags::CheckBox.new(object_name, method, self, checked_value, unchecked_value, options). 
end

Here your form.check_box under a form_with of an object so the object_name is that object name call_up, method here is what object params you want to post player_ids, checked_value and unchecked_value are the values of that params when user submit the form, they will be send as an alternative checked/unchecked array of each checkbox [0, 1, 0, 1, ...], if you just want to send only checked values, just set unchecked_value = nil.

<td><%=form.check_box :player_ids, {multiple: true, skip_default_ids: false, class: "form-check-input"}, player.id, nil %></td>

One more thing, your controller will receive the has params object_name => {..., method: [...]}, so you need to permit that array:

def call_up_params
  params.require(:call_up).permit(:name, player_ids: [])
end
  • Related