简体   繁体   English

ruby on rails使用Typeahead(bootstrap)实现自动完成搜索

[英]ruby on rails implement search with auto complete using Typeahead (bootstrap)

I want to add auto-complete to my search bar. 我想在搜索栏中添加自动完成功能。 But when I submit the completed user I get this url : 但是当我提交完成的用户时,我得到以下网址:

/users?utf8=✓&search=Thomas

Instead of /users/23 代替/users/23

My controller 我的控制器

@users = User.find(:all, :select=>'name').map(&:name)

The Javascript Javascript

 <%= javascript_tag "var autocomplete_items = #{ @users };" %>

 <script type="text/javascript">
            jQuery(document).ready(function() {
                $('#auto_complete').typeahead({source: autocomplete_items});
            });
 </script>

My form 我的表格

<%= form_tag users_path, :method => :get do %>
  <%= text_field_tag :search, params[:search], :id => "auto_complete" %>
<% end %>

Thanks for your help 谢谢你的帮助

From what I can glean from the Bootstrap docs, typeahead is only designed to do just that - type ahead of text. 从Bootstrap文档中可以得出的结论是, typeahead只能做到这一点-在文本之前输入。 It just takes your input, sees if there's something in its source that matches the input and offers some alternatives for completing the input. 它仅接受您的输入,查看其源中是否有与输入匹配的内容,并提供一些替代方法来完成输入。 If the user chooses an alternative, typeahead fills in the selected string. 如果用户选择其他选项,则请提前输入所选字符串。

So the only thing you get is a string in an input field. 因此,您唯一得到的就是输入字段中的字符串。

Typeahead does not know how to construct a link like the one you need: /uses/23 Typeahead不知道如何像您需要的那样构造一个链接: /uses/23

Event if Bootstrap typeahead knew how to do that, you haven't provided it with the needed information since you're only providing it with the names of the users. 如果Bootstrap typeahead知道如何做到这一点,那么您没有向其提供所需的信息,因为您仅向其提供了用户名。

I think what you want to do is: 我想您想做的是:

  • Send both user names and user paths to the view 将用户名和用户路径都发送到视图
  • Use some kind of autocomplete widget that can trigger a callback when an item is selected. 使用某种自动完成小部件,当选择一个项目时,它可以触发回调。
  • Use the callback to navigate to the selected user path when a user is selected 选择用户后,使用回调导航到选定的用户路径

I'm not entirely familiar with Bootstrap's typeahead - you may be able to do this stuff with it. 我对Bootstrap的预输入并不完全熟悉-您也许可以用它来做这些事情。

But I argue for using something that's better documented, like jQuery UI:s autocomplete. 但是我主张使用更好的文档,例如jQuery UI:s autocomplete。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM