Saturday, June 22, 2013

Rails 3 and autocomplete

For a simple use case,  follow the README - https://github.com/crowdint/rails3-jquery-autocomplete.   But in my use case, I have to pass {lat, lng} as the selection value instead of default 'label' name.

Spent couple of hours and reading thru' many stackoverflow articles and the following response in stackoverflow shed light on how to do this.

http://stackoverflow.com/questions/3188157/how-to-set-up-jquery-ui-autocomplete-in-rails/3222639#3222639

To return additional data along with selected value, here is the format of the controller response for autocomplete:



Controller:
def autocomplete_location_name
    @locations = Location.select("id,a_locality,a_region,a_country, a_lat, a_lon").where("name like ?", "%#{params[:term]}%")
    render json: @locations.map { |a| { :id =>  a.id, :lat => a.a_lat, :lon => a.a_lon, :label => [a.a_locality,a.a_region,a.a_country] * ', ' } }

end




Note: the :label is the display text and all other elements will be returned as part the callback_data.item.

index.html.erb:
<%= autocomplete_field_tag 'name', '', 'locations/autocomplete_location_name'%>

To test what is returned after selection add the following to application.html.erb:
<script>
$(document).ready(function(){
    $('#name').bind('railsAutocomplete.select', function(event, data){
  /* Do something here */
  alert(JSON.stringify(data, null, 4));
});
});
</script>




No comments :