← Back to Upcase

Basic Search


(Upcase ) #1

© 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

(Arslan Ali) #3

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


(Nick Noble) #4

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?