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.
<!-- projects/index.rhtml -->
<% form_tag projects_path, :method => 'get' do %>
<p>
<%= text_field_tag :search, params[:search] %>
<%= submit_tag "Search", :name => nil %>
</p>
<% end %>
# 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
本文介绍了一种在Ruby on Rails应用中实现简单搜索表单的方法。通过展示具体的代码示例,包括视图部分的表单创建及控制器与模型中的搜索逻辑实现,使读者能够快速掌握如何在项目中加入搜索功能。
121

被折叠的 条评论
为什么被折叠?



