开发者

RoR live-search (text_field_with_auto_complete) submit

I have a "Movies" and a "Actors" table and "Casts" as join-model. To be more specific "Casts" has movie_id, actor_id and rolename. I want in "Movies" form to add a live search to search through actors and a "rolename" text_field and save those to "Casts". I don't know if text_field_with_auto_complete is the right choice but i prefer not to use much javascript because i am not familiar with it. I've been searching all over the internet to find开发者_C百科 something similar to this without any result. I've manage to get it working with "@actors.each do" but it makes a very long list.


It's not a plugin, but with a little jQuery magic, you can make use of http://github.com/chadisfaction/jQuery-Tokenizing-Autocomplete-Plugin. The nice thing about this is that since it is pure JS in its implementation, you can create the AJAX call yourself in Rails and only display what you want. It even allows you to add a stylesheet to the dropdown if you want to make it more Facebook like. In your controller, add a function so the AJAX call will return a list of rows in 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

In the view, add the following code:

<%= 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>


See text_field_with_auto_complete inside form_for

In the auto_complete controller action, make sure your SQL query is restricting the actors names using the passed param.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜