0

I m getting the computer_ids of user like that

<%= check_box_tag "user[computer_ids][]", computer.id, @user.computers.include?(computer) %>

If I choose at least one from checkbox array, that's fine. But if I did not choose any thing it give me an array like that

undefined method `[]' for nil:NilClass

That's because there is no parameter comes. I did not find a solution. The relation is habtm

I'm try to control it is empty or not

if ( !(params[:user][:computer_ids].empty?)  )

EDIT:

since computer_ids is the only parameter in users it didn't understand what params[:user] is and that's why it gives an error.

if ( !(params[:user].present?)  ) , has solved the problem
Ramazan Zor
  • 209
  • 1
  • 14

1 Answers1

1

Add hidden field above all check-boxes with empty value. It will be sent in case user didn't check any check-boxes like:-

<%= form_for @user do |f| %>
    <%= hidden_field_tag "user[computer_ids][]", nil %>
    <% Computer.all.each do |computer| %>
        <%= check_box_tag "user[computer_ids][]", computer.id, @user.computers.include?(computer) %>
    <% end %>
    <%= f.submit 'Submit'%>
<% end %>

Reject blank values from params like:-

params[:user][:computer_ids] = params[:user][:computer_ids].reject { |c| c.empty? }
user3506853
  • 814
  • 5
  • 3