Search code examples
ruby-on-rails-4simple-formmultiple-select

Ruby on Rails - Selected values are not working as expected in multiple: true (simple_form)


In my form, I have an f.select with multiple: true, but select doesn't work if it's not hardcoded in.

This is my form in new view:

= f.select :os, get_uniq_objects(:os), {}, {multiple: true }

My helper

def get_uniq_objects(obj)
  somethings.pluck(obj).uniq
end

My controller

def campaign_params
      params.require(:something).permit(os:[])
end

In new view, when OSs are selected, the result would saved as ['Linux', 'Windows'] so in my edit view I do as below but nothing gets selected:

= f.select :os, options_for_select(get_uniq_objects(:os), @something.os), {}, { multiple: true}

BUT if I hardcode them as below, everything works fine. I've even double checked what @something.os is by adding it to my view and its exactly like the hardcoded code.

= f.select :os, options_for_select(get_uniq_objects(:os), ['Linux', 'Windows']), {}, { multiple: true}

I'm not sure what I've done wrong here. Any help is appreciated and thanks in advance!


Solution

  • Taking a closer look into what value f.select got, helped me this solve this issue.

    Value that was pass to it was as follow:

    ["Linux", "Windows"]
    

    But for some reason, f.select got this array (with backslashes):

    [\"Linux\", \"Windows\"]
    

    This is my solution. In my model I did a gsub to change the saving values to string from an array:

    before_save do
      self.os_name.gsub!(/[\[\]\"]/, "") if attribute_present?("os_name")
    end
    

    so ["Linux", "Windows"], would become Linux, Windows

    and I changed my f.select to following:

    = f.select :os, options_for_select(get_uniq_objects(:os), @something.os.split(/\W+/)), {}, { multiple: true}
    

    I did .split(/\W+/) to change the string to an array that f.select would accept.