Last active
December 19, 2015 16:58
-
-
Save sapienza/5987322 to your computer and use it in GitHub Desktop.
Simple search with Ruby on Rails ;)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #routes | |
| match 'posts/search(/:search)' => 'posts#search', as: 'post_search' | |
| #model | |
| def self.search(search) | |
| search_condition = "%" + search + "%" | |
| find(:all, :conditions => ['title LIKE ? OR content LIKE ?', search_condition, search_condition]) | |
| end | |
| #controller | |
| def search | |
| return redirect_to posts_path if params[:search].nil? | |
| @posts = Post.search params[:search] | |
| end | |
| #views | |
| <%= render :partial => 'posts/search' %> | |
| #partial posts/search | |
| <%= form_tag post_search_path, :method => :get do %> | |
| <%= text_field_tag :search, params[:search], :id => 'search_field' %> | |
| <%= submit_tag "Search", :name => nil %> | |
| <%= link_to_function "Clear", "$('search_field').clear()" %> | |
| <% end %> | |
| #search.html.erb | |
| <ul> | |
| <% @posts.each do |grant| %> | |
| <li><%= link_to grant.title, | |
| :action => 'show', :id => grant.id %></li> | |
| <% end %> | |
| </ul> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment