Rails3で検索機能の実装
Rails3で検索機能を実装する方法です。
meta_searchってgemがいい感じだったので、実装した内容をメモっておきます。
scaffold
例としてメモアプリをscaffoldで作成しました。これに検索機能を追加していきます。
$ rails new sandbox $ cd sandbox $ rails g scaffold memo title:string content:text $ rake db:create $ rake db:migrate
検索機能に必要なgemをインストール
meta_search(検索)、will_paginate(ページング)をインストールしました。
Gemfile
gem "meta_search" gem "will_paginate", "~> 3.0.pre2"
$ bundle install
コントローラの実装
class MemosController < ApplicationController # GET /memos # GET /memos.xml def index @search = Memo.search(params[:search]) # メモの検索条件 @memos = @search.paginate(:page => params[:page]) # メモの検索結果 respond_to do |format| format.html # index.html.erb format.xml { render :xml => @memos } end end (以下、省略) end
ビュー(app/views/memos/index.html.erb)の実装
検索部分
<%= form_for @search, :url => memos_path, :html => {:method => :get} do |f| %> <%= f.label :title %> <%= f.text_field :title_contains %><br /> <%= f.label :created_at %> <%= f.datetime_select :created_at_greater_than_or_equal_to, :include_blank => true %>〜 <%= f.datetime_select :created_at_less_than_or_equal_to, :include_blank => true %><br /> <%= f.submit %> <% end %>
ソートリンク
<%= sort_link @search, :title %>
ページング
<%= will_paginate @memos %>
感想
検索項目を増やしたい場合は、ビューの修正だけで簡単に増やせるので便利だと思います!