Reputation: 1002
I am using rails 4. I have tried to use auto-complete in my application. But when installing autocomplete , it throws error like could not find generator autocomplete:install.
Please guide me how to use autocomplete in my application.
In View
<%= simple_form_for @vehicle_driver,remote: true, html: {class: 'form-inline form-horizontal vehicle_driver' }, :validate => true do |f| %>
<div class="control-group string optional vehicle_driver_vehicle_code">
<label class="string optional control-label" for="vehicle_code">Vehicle</label>
<div class="controls">
<%= f.select :vehicle_id, vehicle_assign_driver, {},{} %>
<%= link_to new_vehicle_path do %>
<span class='icon-plus-sign'></span><br>
<% end %>
</div>
</div>
<div class="control-group string optional vehicle_driver_driver_name">
<label class="string optional control-label" for="driver_name">Driver</label>
<div class="controls">
<%= f.select :driver_id, driver_list, {},{} %>
<%= link_to new_driver_path do %>
<span class='icon-plus-sign'></span><br>
<% end %>
</div>
</div>
<div style="padding-left:15em">
<%= f.button :submit, {value:'Assign', class: 'btn btn-primary'} %>
<span id="updated1" class="inline icon-ok hidden" style="display: none;">Assigned Successfully</span>
</div>
<% end %>
In Application controller
def driver_list
Driver.where(:driver_allotted => false).map{|i|[i.first_name.capitalize, i.id]}
end
I am using f.select for displaying driver list in drop down. Instead of that it will show on auto-complete.
How to use auto-complete in simple form . Please Share your ideas
Upvotes: 3
Views: 1427
Reputation: 4367
It's very simple:
In view you need a text_field.
In your js file:
$( "#driver_id" ).autocomplete({ source: "/controller_name?filter_key=attr_name", minLength: 0 });
In your controller you will get params[:term]
with the text_field value:
if params[:term]
@drivers = Driver.where(filter_key.to_sym => params[:term]).map(&filter_key.to_sym)
end
Please DO NOT put your drivers code in application_controller, put it in driver_controller.
Upvotes: 2