Autocomplete over Associations in Rails 4

(Comments)

When creating a simple web application for a friend I found out the Formtastic (later Simple Form) solution for a belongs_to: :customer associaton, a <SELECT> was not the best. It simply loaded all customer names and ids into the HTML (more than 15 thousand!). Among the solutions I thought an Autocomplete field to be the best.

A sample showed me the basics and after some searching I found the well documented rails4-autocomplete gem (that led to also adding jquery-ui-rails, sadly).

To use it from the Order model I had to create a delegate for the customer name:

Class Order < ActiveRecord::Base
  ...
  delegate :name, to: :customer, prefix: true
end

... and a service in the OrderController:

Class OrdersController < ApplicationController
  ...
  autocomplete :customer, :name, full: true
  ...
end

... a new route for the service:

resources :orders do
  get :autocomplete_customer_name, on: :collection
end

... and add decorations to the erb:

<%= f.input :customer_name, as: :autocomplete, url: autocomplete_customer_name_order_path %>

First test... and nothing! Service not called at all! After fiddling with the javascript I found out Zurb foundation-rails had added an app/assets/javascripts/vendor/jquery.autocomplete.js that conflicted with jQueryUI autocomplete. I searched where it could be being used, and found nothing so I just removed it.

And now it worked!

But it only brought in the customer name... This was enough accordingly with this railscasts solution: finding by name. But was unacceptable for customers because we may have name conflicts.

Luckly the rails4-autocomplete generated controller method already returned the customer id so I took advantage of its data-id-element feature:

<%= f.input :customer_id, as: :hidden %>
<%= f.input :customer_name, as: :autocomplete,
   url: autocomplete_customer_name_order_path,
   input_html: { 'data-id-element' => '#order_customer_id' } %>

Voilá! Now the chosen customer got updated into the order.

Current rating: 3.2

Comments