简体   繁体   中英

Rails: How can i set empty array with current parameters

my application want to send empty array if check_box_tag is unchecked

This is my hidden_field_tag code

<%= hidden_field_tag('user[roles][]') %>

now i get parameter

"user"=>{"roles"=>[""]}

i want to instead with

 "user"=>{"roles"=>[]}

please guides

You cant prevent rails from assigning "" as default value but you can remove empty strings from an array in the controller like this:

@arr = params["user"]["roles"].map{ |x|
  x unless x.empty?
  nil if x.empty?
}.compact

The map replaces empty strings with nil and compact removes the nil values from the array.

<%= hidden_field_tag('user[roles][]', nil) %>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM