Simple Search Form
A search form is quite different than other forms, this is because it does not deal with model's attributes. See a good way to add a simple search form in this episode.
搜索表单跟其他表单不同,它并不对model的属性进行操作。这节来看如何添加一个简易的搜索表单。
<!-- projects/index.rhtml -->
<% form_tag projects_path, :method => 'get' do %>
<p>
<%= text_field_tag :search, params[:search] %>
<%= submit_tag "Search", :name => nil %>
</p>
<% end %>
这里用form_tag将表单数据提交到projects_path(RESTful routes生成的指向index的路由),方法get
form_tag与form_for的区别:
form_for用来与model绑定,表单中的数据是给model的属性提供值。
而form_tag表单中的值可以用户自定义传送。
projects_controller.rb
def index
@projects = Project.search(params[:search])
end
# models/project.rb
def self.search(search)
if search
find(:all, :conditions => ['name LIKE ?', "%#{search}%"])
else
find(:all)
end
end
本文转自 fsjoy1983 51CTO博客,原文链接:http://blog.51cto.com/fsjoy/143566,如需转载请自行联系原作者