example for using jquery auto complete plugin with rails

后端 未结 1 894
暖寄归人
暖寄归人 2021-01-07 01:53

It would be of great help if some one could help me with an example to implment auto complete feature in my rails application.I tried the jquery auto complete plugin.I was

相关标签:
1条回答
  • 2021-01-07 02:33

    Have a look at the Gem rails3-jquery-autocomplete. It should be the base for your implementation. There is even an example application that explains each step you have to take to include it in your application.

    At Railscasts.com, you will find an episode that explains how to use it: Autocomplete-association (revised)

    If it does not work at all for you, you should come back and ask concrete questions. From your above question, it is not clear where you want to use autocomplete. It is normally used to establish an (additional) association to another object, where you want to replace the drop-down-list or selection-in-list or list of checkboxes by the autocomplete field.

    There is an alternative, if you want to have more than one thing selected, have a look at the Railscasts episode "Token Fields". Because your comment states that this is what you want to do, here are some hints how to do it (copied from my application, you have to replace it by your context, it is a short version of Railscasts 258):

    • Install JQuery Tokeninput into your Rails application.
    • Ensure that your application knows jquery (by using Gem jquery-rails)
    • Include the Javascript file jquery.tokeninput.js into your application (syntax depends on the version you are using).
    • Include the following code in your model (User ??):

      class User < ActiveRecord::Base
        attr_accessible :name, :tester_tokens
        has_many :testers
        attr_reader :tester_tokens
      
        def tester_tokens=(ids)
          self.tester_ids = ids.split(",")
        end
      
      end
      
    • Include in your application.js the following code:

      $(function () {
        $('#user_tester_tokens').tokenInput('/testers.json', { 
            crossDomain: false,
            prePopulate: $('#user_tester_tokens').data('pre') })
      }); 
      
    • Include in your TestersController the following code:

      class TestersController < ApplicationController
        def index
          @testers = Tester.where("name like ?", "%#{params[:q]}%")
          respond_to do |format|
            format.html
            format.json { render :json => @testers.map(&:attributes) }
          end
        end
      end
      
    • Change in your view code the following line:

      = form.text_field :tester_tokens, "data-pre" => @user.testers.map(&:attributes).to_json
      

    You will find the explanation for all these steps, and some more background at Railscasts episode 258.

    0 讨论(0)
提交回复
热议问题