简体   繁体   中英

Stored value not being set to nil when user deselects all options - rails / simple_form

I have the following form input which is working, except for one small 'bug'

<%= f.input :secondary_role, :collection => UseridRole::VALUES, :include_blank => false,:label => "Secondary Role(s):", :input_html => {  :class => " simple_form_bgcolour simple_form_position overide_selection_field_width", :size => 4, multiple: true }, include_hidden: false, :hint => "Hold shift to select multiple roles" %>

My user's secondary role is stored in my DB as an array:-

"secondary_role": ["moderator"]

My problem is that in cases where the user has set a secondary role, that can't be un-set by deselecting the option. Nothing happens when an option is deselected in the list and saved. The above moderator can only be removed by selecting another option. How can I make the array empty upon deselection of all?

Remove the include_hidden: false option; the hidden field is there to make this work automatically.

(Otherwise, you'll need to handle the situation manually in the controller action that receives the form submission.)

So as @matthewd pointed out, the solution was to remove the include_hidden: false option, although this introduced another issue of a blank array item being added to my roles array.

So, I added the below method to trigger before every save and remove any blank array entries:

  def remove_blank_entry
    secondary_role = self.secondary_role
    if secondary_role.include? ""
      secondary_role.delete("")
    end
  end

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