使用自动完成搜索的Rails实现
问题描述:
我不确定如何将自动完成表单添加到我的搜索功能中。使用自动完成搜索的Rails实现
<%= 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
现在这个工作非常适合搜索,但它,我想让它显示结果,我正在写它,我不能使用jquery自动完成,因为它是两个对象。
答
使用Twitter typeahead。有一些例子在这里:
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
}
]);
我将如何钩住我的模型? – Jseb 2013-03-03 21:48:55
我要编辑我的答案,向您展示它是如何工作的 – Alfonso 2013-03-03 21:56:13
谢谢,我正在阅读他们的api有点让人困惑第一次看到 – Jseb 2013-03-03 21:58:24