Basic Search

© 2012 - 2017 thoughtbot, inc. Upcase, the design of a robot, and thoughtbot are registered trademarks of thoughtbot, inc.


This is a companion discussion topic for the original entry at https://thoughtbot.com/upcase/videos/intermediate-rails-9

Why did the author use LEFT JOIN instead of INNER JOIN in the search query?

Mine doesn’t seem to be showing results, and I can’t find any typos – where did I go wrong?

My code:

# views/hashtags/show

<h1>#<%= @search.term %></h1>

<%= render @search.results%>
# hashtags controller

class HashtagsController < ApplicationController
  def show
    @search = Search.new(term: hashtag)
  end

  private

    def hashtag
      params[:id]
    end
end
# services/search

class Search
  attr_reader :term
  
  def initialize term:
    @term = term
  end

  def run
    ShoutSearchQuery.new(term: "##{term}").to_relation
  end

  alias results run
end
# queries/shout_search_query

class ShoutSearchQuery
  def initialize(term:)
    @term = term
  end

  def to_relation
    Shout.joins("LEFT JOIN text_shouts ON content_type = 'TextShout' AND content_id = text_shouts.id").where("text_shouts.body LIKE ?", "%#{term}")
  end

  private

    attr_reader :term
end
# Shout model

class Shout < ApplicationRecord
  belongs_to :user
  belongs_to :content, polymorphic: true

  validates :user, presence: true

  delegate :username, to: :user
end

Sidenote:

It would be really nice to be able to see and diff the final source code. Is there a repo available?

I second that. The videos are great, however it’s really hard to utilise all the knowledge if you can’t look at the source code and instead need to try and painstakingly look for the interesting parts of the code in the videos.

Hello Nick,
The reason your results don’t show anything is that you have forgotten something in your where condition inside your query.
You missed the second %. In your code you have where("text_shouts.body LIKE ?", "%#{term}") instead of where("text_shouts.body LIKE ?", "%#{term}%").
I hope this answer helped you resolving your issue and that you can continue the course :slight_smile:.