#37 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.
<!-- 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

你可能感兴趣的:(search)