FBJS autocomplete/typeahead in Rails

Facebook released FBJS a while back to allow some JavaScript in Facebook applications. It is basically a JavaScript parser that modifies the scripts to make them a little bit safer. Ray and I have been working on a new app for OnMyList and we want an text input box with autocomplete to suggest names. If you’re using Rails outside of Fb, or if you’re using IFRAME for your Fb app, then autocomplete is really easy, you basically only need to add 2 lines, one like this in the controller:

auto_complete_for :user, :name

where user is the model name and name is the field you want to autocomplete for inside the users table. And in the view, you add something like this:

< %= text_field_with_auto_complete :user, :name %>

This will generate everything you need to have an autocomplete textbox. However, this assumes that you can load the Prototype and Script.aculo.us js libraries, and if you want your app to use FBML, these libraries do not work as FBJS.

Autocomplete with FBML is a little bit more work. Facebook’s Developer Wiki has an FBJS typeahead with AJAX example, I don’t love hacking JavaScript so I just borrowed the code there to use in my view. That page shows you how to write a PHP AJAX endpoint, to make it work with Rails, I tried to make it so it would take the data returned by the auto_complete_for method, it turned out to be a bit too much JS changes for me, I’d like to leave the FBJS as close to original as possible. I also prefer writing Ruby more than JS so I ended up implementing the endpoint in the controller, it took a while to get it working, so to possibly save you some time, here’s how it looks like at the end:

def auto_complete_for_user_name
  names = User.find(:all,
    :conditions => [ 'LOWER(name) LIKE ?', params[:suggest_typed].downcase + '%'],
    :order => 'name ASC',
    :limit => 10).map { |n| n.name }
  render :text => "{fortext:#{params[:suggest_typed].to_json},results:#{names.to_json}}"
end

I tried render :json but it didn’t work, coz the typeahead JS is expecting a certain format, but render :text works just fine. Hope you find this post helpful. I will also edit that Wiki entry to include the Rails version of the handler.

Technorati Tags: , , , , , , ,

One thought on “FBJS autocomplete/typeahead in Rails

  1. Pingback: ayn blog » beta fbml tag for autocomplete

Leave a Reply