Freitag, 20. Juni 2008

Auto Complete Related Models

Here is an auto_complete example that works accross 2 related models:

has_many :messages

belongs_to :movie

This went in the messages new view.
<%= text_field_with_auto_complete :movie, :movie_name, {:size => 50}, {:url => formatted_movies_path(:js), :method => :get, :param_name => 'search'} %>

as you cannot use the regular auto_complete_for helper for auto complete across models the text_filed_with_auto_complete needs to have a few more things added to it.

:movie is the model name for the auto complete
:movie_name will contain the input from the user
The first {} contains the options for the input field
The second {} contains the options for the java script

in the first {} the field size is set to 50 with :size=>50
in the second {} the
:url tells the auto complete where to go to get its information to give back to the client. In this case its the path to the index function of the movie controller. (:js) means java script is the format to pass around
:method make rails get information rather then post information (which normally happens with the information from an input field)
:param_name set the name of the params hash key with the information being typed into the field.

This was how the messages controller handled the create
def create
@message =[:message])> params[:movie][:movie_name])

This is what happened on the movie index method
def index
@movies = Movie.find(:all, :limit => 20, :conditions => ['title LIKE?', "%#{params[:search]}%"])

respond_to do |format|
format.html # index.html.erb
format.js #{ render :html => @movies }
format.xml { render :xml => @movies }

as you can see in the above the index.js.erb file will be rendered when java script is calling this controller method.

This is what the index.js.erb file looks like

<%= auto_complete_result @movies, :title %>

This is a help method from auto complete which renders back the title value for the objects contained in the @movies instance.

!!!!DONT FORGET to add the java script librarys in the layout.
<%= javascript_include_tag :defaults %>

One last thing: Here is the CSS for the auto_complete to add the CSS being used for model so that the defaults can be overridden.

.auto_complete {
/*width:250; */
overflow: hidden;
white-space: nowrap;
border:1px solid #888;
color: black;

.auto_complete ul {
list-style-type: none;
color: black;

.auto_complete ul li.selected
background-color: #fff; /* #bbf; */
color: black;

.auto_complete ul li {
list-style-type: none;
color: black;

Keine Kommentare: