Ajaxによるインクリメンタルサーチ

ビュー

  • index.rhtml を作る.
  • div と CSS で2段カラム構成にする.

0.3秒毎に 'keyword' というテキストフィールドを監視します.変化があれば,search_remote アクションを実行し,その結果を hits というid属性を持つ div タグに表示させる.

[app/views/books/index.rhtml]

<div class="main">
  <h1>Book List on Rails</h1>
  <div id="hits">
    <%= render :partial => 'book_list' %>
  </div>
</div>

<div class="sidebar">
<%= form_tag %>
  Inc Search: <%= text_field_tag 'keyword', '', :autocomplete => "off" %>
  <%= observe_field 'keyword',
    :frequency => 0.3,
    :url => { :action => 'search_remote' },
    :with => "'keyword=' + encodeURIComponent(value)",
    :update => 'hits' %>
<%= end_form_tag %>

<br>
  <% for book in @books %>
    <%= book.title %><br>
  <% end %>
</div>
  • JavaScript,gray2.css の読み込み
  • /public/stylesheets/の下に,gray2.css を追加

http://www.tdiary.org/archive/theme/msg00566.html ←ココから頂きました.

[app/views/layouts/books.rhtml]

  <%= stylesheet_link_tag 'scaffold' %>
  
  <%= stylesheet_link_tag 'gray2'%>
  <%= javascript_include_tag "prototype" %>

</head>
<body>
  • partial テンプレート,'book_list'のファイル名には,「_」を付加する.
[app/views/books/_book_list.rhtml]

<% @books.each do |book| %>
<div class = "day">
  <h2>
    <%=h book.title %>
  </h2>
  <div class = "body">
    <div class = "section">
      <%=h book.review %>
    </div>
    <div class = "referer">
    </div>
  </div>
</div>  
<% end %>  

コントロール

  • index を書き換えて,search_remote アクションを新規追加.
[app/controllers/books_controller.rb]

  def index
#    list
#    render :action => 'index'
#    
    @book_pages, @books = paginate :books, :per_page => 10
  end

  def search_remote
    @books = Book.find(:all, 
      :conditions => ['title like ?', '%' + params[:keyword] + '%'], :limit => 50)
    render :partial => 'book_list'     
  end


これはなかなか使えるです!