Rails select2 ajax tags

jquery, jquery-select2, ruby-on-rails, select2-rails

Solution

The select2 does not know what field you want to use from the data you passed back. Assuming it is the `name` field, add this function separately (not in select2):

function format(item) { return item.name; }

and the two following options to select2:

formatSelection: format,
formatResult: format

Problem

I'm using the select2 jquery gem. I'm trying to get the list of topics matching what the user types. It's not working as expected and i've spent all day trying to find out why. I keep getting this error in the console ``` Uncaught TypeError: Cannot call method 'toUpperCase' of undefined select2.js?body=1:363 Uncaught TypeError: Cannot call method 'localeCompare' of undefined ``` The second error links to the js file on this line ``` return this.text.localeCompare(term) === 0; ``` Is there something i'm doing wrong? Thanks in advance. My route: ``` get '/topic/topic_list' => 'topic#topic_list' ``` In my Topic controller i have: ``` def topic_list @topics = Topic.order(:name) respond_to do |format| format.html format.json { render json: @topics.where('name like ?', "%#{params[:q]}%") } end end ``` Topic js file ``` $(function () { $('#story_topic_list').select2({ tags: true, width: '100%', tokenSeparators: [","," "], createSearchChoice: function(term, data) { if ($(data).filter(function() { return this.text.localeCompare(term) === 0; }).length === 0) { return { id: term, text: term }; } }, multiple: true, maximumSelectionSize: 5, formatSelectionTooBig: function (limit) { return 'You can only add 5 topics' }, ajax: { dataType: 'json', url: '/topic/topic_list.json', data: function (term, page) { return { q: term }; }, results: function(data, page) { return { results: data }; } } }) }); ``` In my form i have ``` <%= f.label :topic_list %> <%= f.text_field :topic_list %> ``` Also the /topic/topic_list.json returns this: ``` [{"id":2,"name":"app","added_by":null,"cover_id":null,"created_at":"2014-03-23T20:12:24.615+00:00","updated_at":"2014-03-23T20:12:24.615+00:00","count":1},{"id":5,"name":"app tech website","added_by":1,"cover_id":null,"created_at":"2014-03-23T20:23:33.754+00:00","updated_at":"2014-03-23T20:23:33.754+00:00","count":1},{"id":3,"name":"tech","added_by":null,"cover_id":null,"created_at":"2014-03-23T20:12:24.668+00:00","updated_at":"2014-03-23T20:12:24.668+00:00","count":1},{"id":4,"name":"website","added_by":null,"cover_id":null,"created_at":"2014-03-23T20:12:24.677+00:00","updated_at":"2014-03-23T20:12:24.677+00:00","count":1}] ```

Original source