Add the search route

# in routes.rb (other code ommitted)
  resources :videos, only: [:show] do
    collection do
      get :search, to: "videos#search" 

  • Nest the search route under the model you are searching ->
  • It’s better to use GET than POST (see

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

The search action in the Controller

# in videos_controller.rb (other code ommitted)

  def search
    @results = Video.search_by_title(params[:search_term])

The search form in the views

<!-- _header.html.haml -->

<!-- in HAML -->
= form_tag search_videos_path, class: "span5 for-search", method: "get" do"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 -->

  - @results.each do |video|
        = link_to video do