我不确定如何为我的搜索功能添加自动完成表单。
<%= form_tag "/search", :method => "get" do %>
<%= text_field_tag :query, params[:query] %>
<%= image_submit_tag "site/blankimg.png", :name => nil %>
<% end %>
我有一个具有自定义操作的 Controller
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
}
]);
关于ruby-on-rails - 自动完成搜索的 Rails 实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15191240/