Rails : simple_form : Getting an empty string from checkbox collection
Asked Answered
S

2

24

I have the following code in my views

<%= f.input :role_names, as: :check_boxes, collection: @program.role_names %>

And whenever I submit the form I am getting values something like ["admin, "moderator", ""] but I was expecting something like ["admin, "moderator"] , why is this?

Moreover I made a inspect element, and there was a <input name="user[role_names][]" type="hidden" value=""> tag after the last check box, within the same control-group. I suppose this is getting added at the last in the params[:user][:recipient_role_names].

How should I handle this? I know I can do a reject(&:blank?) but is there a cleaner way on params[:user][:recipient_role_names]? I also want to know why the input element is getting added? Is it a bug in simple form or I have done something wrong?

Other info:

  1. simple_form gem version: 2.0.4
  2. rails version: 3.2.8
Saucier answered 27/12, 2012 at 11:46 Comment(0)
M
23

It's a Rails' feature. You'll be able disable it in Rails 4. You can read more about this on simple form issue #603 and Rails issue #5402

Madura answered 27/12, 2012 at 11:53 Comment(2)
perfect.. ll accept in 5 mins.. some time constraint.. cant accept now.. Btw I would love to understand why.. do you have any idea why this is a rails feature? I mean why they made this feature? and is this supposed to fix somethings else, if so what was that? It would be great if you could explain about it a little.. thx in advance..Saucier
you can read explanation here api.rubyonrails.org/classes/ActionView/Helpers/… (it's Gotcha section)Madura
M
2

Just add include_hidden: false to your input params:

<%= f.input :role_names, 
  as: :check_boxes, 
  collection: @program.role_names, 
  include_hidden: false 
%>

And the empty string value won't be sent in the array.


Obs: I've just added the simple_form input code here for quick reference, as it was Vasily's answer that pointed me in the right direction. Thank you

Michaels answered 27/7, 2021 at 0:38 Comment(1)
removing the hidden input makes checkboxes uncheckable, which is not desiredNightshade

© 2022 - 2025 — McMap. All rights reserved.