ruby on rails - select2 AJAX'd to a model, configuration -
so, discovered select2. awesome. i'm trying figure out how use it, server side ajax / json. of examples see, everywhere, show using select2 jsonp retrieve data external source. feel should easier if calling local model, no? i'll right nitty gritty. json returns value, searchbox doesn't autocomplete, stays blank.
view html:
<%= form_tag request_pal_path, remote: true %> <%= hidden_field_tag :email, nil, class: 'ui-corner-all' %> <%= submit_tag "send request", class: 'button' %> <% end %>
and calling js on it:
$(document).ready(function() { $("#find_user #email").select2({ width: '400px', placeholder: "find user...", minimuminputlength: 1, multiple: false, id: function(obj) { return obj.id; // use slug field id }, ajax: { // instead of writing function execute request use select2's convenient helper url: "/users", datatype: 'json', data: function (term, page) { return { q: term, // search term page_limit: 10 }; }, results: function (data, page) { // parse results format expected select2. // since using custom formatting functions not need alter remote json data return {results: data}; } }, formatresult: formatresult, formatselection: formatselection, escapemarkup: function (m) { return m; } }); }) function formatresult(user) { return '<div>' + user.name + '</div>'; } function formatselection(user) { return user.name; }
which goes controller, user index action
:
def index @find = user.where('name ?', "%#{params[:q]}%") @users = @find.where('id not in (?)', current_user.id).order('random()').page(params[:page]).per(100) @title = "potential pals" respond_to |format| format.html format.js { @find = @find @users = @users } format.json { @find } end end
and made .json file respond (not sure if necessary):
<% @find.each |user| %> <%= user.name %> <% end %>
so, json working, extent. if in developer console, shows response coming http://localhost:3000/users.json?q=tay
, or whereever, , returns single value, taylor
(in instance). when search inside of select2 search box, spins , spins, no results. no console errors, that's nice, ha. thoughts? thanks!
i guess problem in .json file, since select2 needs json array or json object. try remove , respond format.json { render json: @find.to_json }
. other code seems ok me.
Comments
Post a Comment