RoR实时搜索(text_field_with_auto_complete)提交

时间:2010-02-10 14:37:09

标签: ruby-on-rails ruby ajax autocomplete

我有一个“电影”和一个“演员”表和“演员”作为连接模型。更具体的“演员”有movie_id,actor_id和rolename。 我希望在“电影”表单中添加实时搜索以搜索演员和“角色名称”text_field并将其保存到“演员”。 我不知道text_field_with_auto_complete是否是正确的选择,但我不想使用太多的javascript,因为我不熟悉它。 我一直在网上搜索找到类似的东西没有任何结果。 我已经设法让它与“@ actors.each do”合作,但它列出了很长的名单。

2 个答案:

答案 0 :(得分:2)

它不是一个插件,但有了一点jQuery魔法,你可以使用http://github.com/chadisfaction/jQuery-Tokenizing-Autocomplete-Plugin。关于这个的好处是,因为它的实现是纯JS,你可以在Rails中自己创建AJAX调用,只显示你想要的东西。如果你想让它更像Facebook,它甚至允许你在下拉列表中添加一个样式表。在您的控制器中,添加一个函数,以便AJAX调用将返回JSON中的行列表:

  def taglist
    tags = []
    sql = "SELECT id,name ... LIMIT 15" # Enter SQL here to produce a possible result set
    result = ActiveRecord::Base.connection.execute(sql)
    # Iterate over the hash values and push them into an array
    result.each { |field| tags.push( {"id" => field[0], "name" => field[1]} ) }
    result.free
    render :json => tags, :layout => false
  end

在视图中,添加以下代码:

<%= javascript_include_tag 'jquery.tokeninput' %>
<%= stylesheet_link_tag 'token-input-facebook' %>
<script type="text/javascript">
jQuery(document).ready(function () {
  jQuery("#actors_role").tokenInput("/actors/rolesearch", {
        allowNewValues: false,
        canCreate: false,
        hintText: "Enter the actor's name or role they played",
  });
});
</script>

答案 1 :(得分:0)

请参阅text_field_with_auto_complete inside form_for

在auto_complete控制器操作中,确保您的SQL查询使用传递的参数限制actor名称。

相关问题