2010/04/10

検索フォームにコダワル

いろんなところで使いそうなので、検索フォームの作り方をまとめてみた。(突っ込みどころは沢山あると思います。)

まず view
<% form_tag request.path, :method => 'get' do %>
<table>
 <tr>
  <td><%= t('common.created_at') %></td>
  <td><%= calendar_date_select_tag(:created_from, params[:created_from], :time => false)%> - <%= calendar_date_select_tag(:created_to, params[:created_to], :time => false)%></td>
 </tr>
 <tr>
  <td><%= t('common.keyword') %></td>
  <td><%= text_field_tag :keyword, params[:keyword], :size => 30 %> ID <%= text_field_tag :id, params[:id], :size => 10 %></td>
 </tr>
 <tr>
  <td>sort_by</td>
  <td><%= select_tag(:sort_by, options_for_select([['created_at', 'created_at'], ['updated_at', 'updated_at'], ['login_at', 'login_at'], ['ID', 'id'] ], 'created_at' ) ) %> <%=select_tag(:sort_dir, options_for_select([[t('common.asc'), 'ASC'], [t('common.desc'), 'DESC']], 'DESC'))%> 
  </td>
 </tr>
 <tr>
  <td></td>
  <td><%= submit_tag t('common.search_with_conditions') %> <input type="reset" value="Reset!"></td>
 </tr>
</table>
<%end %> 
リセットボタンは便利。また、select_tag にオプションを渡す場合は options_for_select を使用。
<%= select_tag(:sort_by, options_for_select([['created_at', 'created_at'], ['updated_at', 'updated_at'], ['login_at', 'login_at'], ['ID', 'id'] ], 'created_at' ) ) %>
selected = 'created_at' を指定している。

controller
    @users = User.full_search(params[:keyword], params[:page], :id => params[:id],
      :created_from => params[:created_from], :created_to => params[:created_to],
      :sort_by => params[:sort_by], :sort_dir => params[:sort_dir]
      )
model
メソッドには自由にパラメータを渡せるように options={} を使う
  def self.x_search(search, page, options = {})
    sql = "((display_name like '%#{search}%') OR (profile like '%#{search}%') OR (first_name like '%#{search}%') OR (last_name like '%#{search}%') OR (email like '%#{search}%') OR (mobile like '%#{search}%'))"

    if options[:id] && options[:id] != ""
      sql << " AND id = '#{options[:id]}'" 
    end

    if options[:created_from] && options[:created_from] != ""
      from = Time.parse(options[:created_from]).to_s(:db)
      # If timezone conversion required use Time.zone.parse(options[:created_to]).utc.to_s(:db)
      sql += " AND created_at >= '#{from}'"
    end
  
    if options[:created_to] && options[:created_to] != ""
      to = Time.parse(options[:created_to]).to_s(:db) 
      sql += " AND created_at <= '#{to}'"
    end
  

    if options[:sort_by] && options[:sort_by] != "" && options[:sort_dir] && options[:sort_dir] != ""
      order = options[:sort_by] + " " + options[:sort_dir]
    else
      order = 'created_at DESC'
    end    

    paginate(:per_page => 30, :page => page, :conditions => sql, :order => order)
  end

0 件のコメント: