Skip to content

Instantly share code, notes, and snippets.

@folivi
Created June 23, 2015 10:21
Show Gist options
  • Save folivi/ef31be070cb8ba320b83 to your computer and use it in GitHub Desktop.
Save folivi/ef31be070cb8ba320b83 to your computer and use it in GitHub Desktop.
Select2 & rails
class SearchController < ApplicationController
respond_to :json
def index
render json: @your_results, each_serializer: YourSerializer , root: :results
end
end
//using lodash (https://lodash.com/docs)
$(document).ready(function(){
$("#search_event").select2({
placeholder: "Search for a object by name",
minimumInputLength: 3,
dataType: 'json',
minimumResultsForSearch: Infinity,
id: function(result){ return result.id;},
ajax: {
url: "/en/search",
data: function (term, page) {
return {
query: term
};
},
processResults: function(data, page) {
//do this if your ajax response is not in the format {id: 'element id', text: 'text' }
var results = [];
_.each(data.results, function(result){
results.push({
id: result.id,
text: result.name
//do this if your ajax response is not in the format {id: 'element id', text: 'text' }
});
})
return {
results: results
}
},
cache: true
},
formatResult: eventResult,
formatSelection: eventSelection,
//escapeMarkup: function (m) { return m; }
});
function eventResult(result) {
return result.name;
//return "<img src=" + event.event.picture + "></>";
}
function eventSelection(event) {
return result.name;
}
});
//sorry about the indentation. bad copy/paste. I'll improve later hopefully :-)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment