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

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 whena you are saving your record.
The improved model:

class Post < ActiveRecord::Base belongs_to :user attr_accessor :user_name def user_name if user_id end end [/ruby] And the part in your view that i left out the last time, but this one is just better in my opinion: [html] < %= 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 ->
    source: "/ajax/users"
    select: (event,ui) ->

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

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.