This demo enables a JQueryUI Autocomplete box on a Ruby on Rails/Rails 3 app. I had wanted to use the rails3-jquery-autocomplete gem, but was not able to get it running. There are many steps which must be followed here. I am assuming Rails 3.2.3.
-
At the command prompt, create a new Rails application:
rails new myapp -J --skip-bundle
(wheremyapp
is the application name) -
Change directory to
myapp
and edit the Gemfile. Remove sqlite3 and replace it with mysql2; add jquery-ui-rails to the assets group; add jquery-rails at version 2.1; and dobundle install
. -
Edit the automatically generated database.yml file to use MySQL2 instead of sqlite3.
-
Run
rails g model brand name
. -
Add data to db/seeds.rb, in the form
Brand.create(:name => "Alpha")
. -
Run
rake db:migrate
. -
Run
rake db:seed
. -
Run
rails generate controller members show
. -
Add the following to the members_controller:
class MembersController < ApplicationController def show @names = Brand.all.map(&:name) respond_to do |format| format.html format.json { render :json => @names } end end end
The effect of this is to produce an array containing the data which the user will choose from in the autocomplete box; and it indicates that this method will respond to JSON by producing the array.
-
Add show.html.erb to views/members as follows:
<h1>Welcome</h1> <%= form_tag :method => :get do %> <%= text_field_tag :brand_name, nil, :class => ‘brand_name’ %> <% end %>
which will identify the text box for autocomplete.
-
Add show.js.erb to views/members as follows:
<%= raw @names %>
-
Add the following to app/assets/javascripts/application.js:
//= require jquery //= require jquery_ujs //= jquery.ui.all
$(function() {
$('.brand_name').autocomplete({ source: '/members/show.json' });
});
-
Add the following to app/assets/stylesheets/application.css:
*= require jquery.ui.all
-
Delete public/index.html.
-
Change the routes to include:
get “members/show” root :to => ‘members@show“
-
Start the rails server.
-
Browse to localhost:3000 and make sure that the autocomplete is working.