开发者

Use Model in Ruby on Rails 3 as source for jQuery autocomplete

I'm using simple jQuery for autocomplete and it works fine when I locally define the list of options in my jQuery. Here's the code (pretty much straight from the jQuery site):

<script>
jQuery(function() {
    var easy = [
        "one",
        "two",
        "three",
    ];
    jQuery( "#tags" ).autocomplete({
        source: easy
    });
});
</script>



<div class="demo">

<div class="ui-widget">
<label for="tags">Tags: </label>
<input id="tags">
&开发者_如何学Clt;/div>

What I want to do is pass the entires on a model I have called user, which has a :name and :business_name attributes, and use the entries in that model for the options. Can I pass this data to my jQuery variable, or is this accomplished another way?


first of all you need two parts to do this:

  • The client (jQuery UI Autocomplete)
  • The backend (Providing the Data)

You can't directly query the model from your javascript code, the query must be done through a controller.

First, have a look at the jQuery Autocomplete Documentation and Examples here.

What you see is that the resulting request will have a parameter called "term", this is what you start typing in the input field.

So the request looks something like

http://yourdomain.com/yourcontroller?term=whatyoutype

What jQuery wants is an array containing hashes in JSON Format like:

[{"label": "Formatted Name to Show in List for first match", "value": 1}, {"label": "Formatted Name for Match #2", "value": 2}]

label: Will be shown in the autocomplete list value: Is the value to be used when you select an entry (e.g. combobox)

I'd suggest to create a controller called UsersController so the request will look like

http://yourdomain.com/users?term=whatyoutype

class UsersController < ApplicationController


  def index

    # general model
    @users  = User

    # check if we should filter results
    if params.has_key?(:term) && !params[:term].empty?
      q = "#{params[:term]}%"
      @users  = @users.where("name LIKE ? OR business_name LIKE ?", q, q)
    end

    # only 20 entries
    @users  = @users.limit(20) 


    # respond in the right format
    respond_to do |format|
      # normal html layout
      format.html
      # json for jquery
      format.json do 
        # make an array
        @users.map! do |u| 
          {
            :label => u.name + " / " + u.business_name,
            :value => u.id
          }
        end
        render :json => @users 
      end
    end
  end
end

Now you can activate the autocomplete like:

jQuery( "#tags" ).autocomplete({
    source: '<%= users_path(:format => :json) %>'
});

users_path(:format => :json) will generate a path like /users.json?term=yoursearchterm

I hope this will work for you

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜