0

I am learning Ruby on rails. I am working with selection box. But the result of the selection box has an empty object along with my selection. Why is it so? Thanks in advance.

This is my form:

<%= form.collection_select(:tag_ids, Tag.all, :id, :name, {}, :multiple => true) %>

This is my tag_ids in parameters:

"tag_ids"=>["", "52"]

Gomathi
  • 23
  • 9
  • Maybe the name attribute for that specific record (52) is `nil`, printed by Rails as an empty string `''`. Have you checked that? – Sebastián Palma Jan 06 '18 at 15:07
  • @SebastianPalma If so how about this "tag_ids"=>["", "41", "48", "49"]. The tag_ids contains only the ids of the tag. I – Gomathi Jan 06 '18 at 15:13
  • 1
    Check this out. This might help https://stackoverflow.com/a/8933085/5304550 – Anmol Jan 06 '18 at 15:32

1 Answers1

0

the empty object is there for the case were nothing is selected.

if the empty object was not submitted when nothing is selected in a put request to an update action in a restful controller then the tag_ids collection would not be updated, whatever was in that collection before the request would remain

Lets say tag_ids = [1,2] before request

if there is nothing selected from the multi-select box then nothing is submitted and even though the intention is to remove all tags, this will not take place.

By adding in the empty string that ensures that it will be submitted to the controller as an empty array (or an array with "" as a value). Empty inputs are not submitted by default.

in this case object.tag_ids=[""] which rails will interpret as an empty array, so tag_ids will now be persisted as empty

mgidea
  • 494
  • 2
  • 6