TodoList: 検索機能を追加 ― 2006年12月13日 12時37分54秒
result 関数を作り、検索結果を保存する。
% cat app/controllers/todo_controller.rb
class TodoController < ApplicationController
scaffold :todo
def result
@keyword = @params[:user][:keyword]
@matches = Todo.find_by_sql("select * from todos where description " + \
"like '%" + @keyword + "%'")
end
end
検索用の画面を作る。
% cat app/views/todo/search.rhtml
<h1>Search</h1>
<div class="form-padding">
<%= start_form_tag :action => 'result' %>
<table>
<%= form_input :text_field, "Keyword", "keyword", :size => 50 %>
;<br/>
</table>
<div class="button-bar">
<%= submit_tag 'Search' %>
<br>
<%= link_to 'List', :action => 'list' %>
</div>
<%= end_form_tag %>
</div>
検索結果の画面を作る。
% cat app/views/todo/result.rhtml
<h1>Matched Todos: <%= @keyword %></h1>
<table>
<tr>
<% for column in Todo.content_columns %>
<th><%= column.human_name %></th>
<% end %>
</tr>
<% for todo in @matches %>
<tr>
<% for column in Todo.content_columns %>
<td><%=h todo.send(column.name) %></td>
<% end %>
<td><%= link_to 'Show', :action => 'show', :id => todo %>&
lt;/td>
<td><%= link_to 'Edit', :action => 'edit', :id => todo %>&
lt;/td>
<td><%= link_to 'Destroy',
{ :action => 'destroy', :id => todo },
:confirm => 'Are you sure?', :post => true %></td>
</tr>
<% end %>
</table
http://localhost:3000/todo/search にアクセスすると、検索語が入れられる。SQL で適合する部分があると、それらが全て羅列される。http://localhost:3000/todo/result に飛ばされるのだ。
最近のコメント