views:

76

answers:

2

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 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.

A: 

See http://stackoverflow.com/questions/244808/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.

Jonathan Julian
+1  A: 

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>
Eric Lubow
Excellent answer. Thank you mate :)
looneygrc