实现实时的搜索
[size=large][/size][color=green]实现实时的搜索
a live search
如果你想着在你的页面进行实时的搜索--就是到你在输入不同关键字的时候,查询的解果将发生变化。
使用 rails 的ajax 辅助方法 创建一个实时 搜索
数据库的迁移
db/migrate/001_create_books.rb:class CreateBooks < ActiveRecord::Migration def self.up create_table :books do |t| t.column :title, :string end Book.create :title => 'Perl Best Practices' Book.create :title => 'Learning Python' Book.create :title => 'Unix in a Nutshell' Book.create :title => 'Classic Shell Scripting' Book.create :title => 'Photoshop Elements 3: The Missing Manual' Book.create :title => 'Linux Network Administrator's Guide' Book.create :title => 'C++ Cookbook' Book.create :title => 'UML 2.0 in a Nutshell' Book.create :title => 'Home Networking: The Missing Manual' Book.create :title => 'AI for Game Developers' Book.create :title => 'JavaServer Faces' Book.create :title => 'Astronomy Hacks' Book.create :title => 'Understanding the Linux Kernel' Book.create :title => 'XML Pocket Reference' Book.create :title => 'Understanding Linux Network Internals' end def self.down drop_table :books endend
接着,使用 script.aculo.us and Prototype
包含到布局中去。
app/views/layouts/books.rhtml:<html> <head> <title>Books</title> <%= javascript_include_tag :defaults %> </head> <body> <%= yield %> </body></html
创建包含index and search 方法的控制器。 search方法对从index视图发过来的ajax调用做出响应。
app/controllers/books_controller.rb:class BooksController < ApplicationController def index end def get_results if request.xhr? if params['search_text'].strip.length > 0 terms = params['search_text'].split.collect do |word| "%#{word.downcase}%" end @books = Book.find( :all, :conditions => [ ( ["(LOWER(title) LIKE ?)"] * terms.size ).join(" AND "), * terms.flatten ] ) end render :partial => "search" else redirect_to :action => "index" end endendindex.rhtml 视图显示了查询字段,并使用observe_field 这一JavaScript 辅助方法在字段中定义一个观察者。
app/views/books/index.rhtml:<h1>Books</h1>Search: <input type="text" id="search_form" name="search" /><img id="spinner" src="/images/indicator.gif" style="display: none;" /> <div id="results"></div><%= observe_field 'search_form', :frequency => 0.5, :update => 'results', :url => { :controller => 'books', :action=> 'get_results' }, :with => "'search_text=' + escape(value)", :loading => "document.getElementById('spinner').style.display='inline'", :loaded => "document.getElementById('spinner').style.display='none'" %>最后,创建一个局部模版, 将查询结果显示为一个书本标题列表。
app/views/books/_search.rhtml:<% if @books %> <ul> <% for book in @books %> <li> <%= h(book.title) %> </li> <% end %> </ul><% end %>[/color]