Autocomplete fields in Rails 3.1 with JQuery-UI pt. 2

1 minute read

As I have written in my previous post, I’m playing with autocompletion in my web app. I have found some new tricks, that will speed up the process. Never liked the find_by_name implementation, but as this example is derived from JQuery.autocomplete plugin behavior, I had no other way. Did some more exploring today and here is what I found out. Because you are using JSON response on the Ajax controller, and JQuery-UI autocomplete handles it perfectly, you can create a hidden field, and put the user_id there, so you have one less request to the database when you are saving your record.

The improved model:

class Post < ActiveRecord::Base
  belongs_to :user
  attr_accessor :user_name

  def user_name
    user.name if user_id
  end
 end

And the part in your view that I left out the last time, but this one is just better in my opinion:

<%= f.label :user_name %>
<%= f.text_field :user_name %>
<%= f.hidden_field :user_id %>

Also, you have to edit the CoffeScript that does the magic for you, so it will return the id into the hidden field:

  $(document).ready ->
    $('#post_user_name').autocomplete
      source: "/ajax/users"
      select: (event,ui) ->
    $("#post_user_id").val(ui.item.id)

An easier way of doing it, and leaner on the database queries, at least one less.

Comments