Build a simple search feature in Rails
Add the search route
# in routes.rb (other code ommitted)
resources :videos, only: [:show] do
collection do
get :search, to: "videos#search"
end
end
- Nest the search route under the model you are searching -> domain.com/videos/search
- It’s better to use GET than POST (see http://guides.rubyonrails.org/form_helpers.html)
Search the database in the model
# in video.rb (other code ommitted)
def self.search_by_title(search_term)
return [] if search_term.blank?
where("title LIKE ?", "%#{search_term}%").order("created_at DESC")
# whatever we pass in the part after the comma(,) replaces the question mark(?) and forms the SQL query
# % before and after search_term are wildcard parameters
end
The search action in the Controller
# in videos_controller.rb (other code ommitted)
def search
@results = Video.search_by_title(params[:search_term])
end
The search form in the views
<!-- _header.html.haml -->
<!-- in HAML -->
= form_tag search_videos_path, class: "span5 for-search", method: "get" do
%input.search-query(name="search_term" type="text" placeholder="Search for videos here")
%button.btn.btn-default(type="submit") Search
<!-- Rails guides provide similar search example code in ERB -->
<%= form_tag("/search", method: "get") do %>
<%= label_tag(:q, "Search for:") %>
<%= text_field_tag(:q) %>
<%= submit_tag("Search") %>
<% end %>
The search results page in the views
<!-- search.html.haml -->
%article.video_category
- @results.each do |video|
%header
.videos.row
.video.col-sm-2
= link_to video do
%img(src="/tmp/#{video.small_cover_url}")