Search code examples
ruby-on-railsselect2-rails

Pass IDs to Rails using Select2


This might be a dummy question. I have a multi-value field on a form with following Select2 settings

jQuery('#mymodel_thing_ids').select2
  multiple: true
  placeholder: "Select things"
  minimumResultsForSearch: -1
  ajax:
    url: "/things.json"
    dataType: "json"
    results: (data, page) ->
      results: data
  formatResult: (data) -> data.name
  formatSelection: (data) -> data.name

When submitting the form with selected things I'm getting

"thing_ids"=>"[],3,2"

i.e. initial value (empty square brackets) and IDs of selected things. But I'd like to have following

"thing_ids"=>"[3,2]"

Is it possible with Select2? And what I'm doing wrong?

UPDATE

To avoid braces in the beginning use value="" when creating an input element.


Solution

  • The problem is that Select2 sends back a string list of items, e.g. "thing_ids" => "1,2,3". What I do when using Select2 in this way is to create accessor methods for thing_tokens and thing_tokens=, which look something like this:

    def thing_tokens
      thing_ids.join(",")
    end
    
    def thing_tokens=(token_string)
      self.thing_ids = token_string.split(",")
    end
    

    Then, in your form, you'll make it be an input for :thing_tokens instead of thing_ids. If you're using Rails 4, make sure you also permit :thing_tokens in your controller.