5

検索機能にオートコンプリート フォームを使用する方法がわかりません。

<%= form_tag "/search", :method => "get" do %>
    <%= text_field_tag :query, params[:query] %>
    <%= image_submit_tag "site/blankimg.png", :name => nil %>
<% end %>

カスタマイズされたアクションを持つ次のコントローラーがあります

   def query
     @users= Search.user(params[:query])
     @article= Search.article(params[:query])
   end

モデルは次のとおりです。

def self.user(search)
 if search
    User.find(:all, :conditions => ['first_name LIKE ?', "%#{search}%"])
  else
    User.find(:all)
  end
end

def self.article(search)
  if search
    Article.find(:all, :conditions => ['title LIKE ?', "%#{search}%"])
  else
    Article.find(:all)
  end
end

これは検索には最適ですが、私が書いている結果を表示したいと思います.2つのオブジェクトであるため、jqueryオートコンプリートを使用できません。

4

1 に答える 1

21

Twitterの先行入力を使用します。ここにいくつかの例があります:

http://twitter.github.com/typeahead.js/examples/

Twitterの先行入力と必要なすべての情報は、https://github.com/twitter/typeahead.js/から入手できます。

使い方

使用法は、「提案された」として持つ予定のデータによって異なります。たとえば、静的データ(常に同じになる)の場合は、次のように実装できます。

$('input.typeahead').typeahead({
  local: ['suggestion1', 'suggestion2', 'suggestion3',...., 'suggestionN']
  #The typeahead is going to load suggestions from data in local.
});

データが変更され、モデルまたはデータベーステーブルからのものである場合は、次のことを試すことができます。

Controller:
def load_suggestions
  @suggestions = MyModel.select(:name) or MyModel.find(:all, conditions: [...]) #Select the data you want to load on the typeahead.
  render json: @suggestions
end

JS file:
$('input.typeahead').typeahead([
  {
    prefetch: 'https://www.mipage.com/suggestion.json' #route to the method 'load_suggestions'
    #This way, typeahead will prefecth the data from the remote url
   }
]);
于 2013-03-03T21:45:50.340 に答える