Ajax select2 with rails
Select2 has a good feature in helping users to search record from a dropdown select option.
However, we should optimize the record by having ajax loading from the database. If we load all the record from the database, it will lead to slow loading and potentially timeout issue.
Gems
- select2-rails
Flow
- When user visit the page, it will not load the select2 option.
- Till the user search from the select2 then only it will trigger an ajax callback to populate user the option with the search result.
Project Setup
- Setup the ajax select2 javascript
$("#item_select2").select2
ajax:
data: (term, page) ->
term: term
page: page
dataType: "json"
quietMillis: 100
results: (data, page) ->
results: data
url: $("#item_select2").data("url")
initSelection: (item, callback)->
id = item.val()
text = item.data('option')
data = { id: id, text: text }
callback(data)
createSearchChoice: (term, data) ->
if $(data).filter(->
@text.localeCompare(term) is 0
).length is 0
id: term
text: term
- The controller callback for select2 search result
def index
@items = Item.where("name ILIKE ?", "%#{params[:term]}%").map{|item| {:id=>item.id,:text => item.name}}
respond_to do |format|
format.json {
render :json => @items
}
end
end
- Input form html to display the select2
<%= f.hidden_field :name, :class=>"select2", :id=>"item_select2", :"data-url" => items_path(:format => :json) %>
Note: You’ll want to retrieve the actual content from the gists and include them in the code blocks above.