Skip to content

Instantly share code, notes, and snippets.

@mladenoff
Last active November 29, 2017 01:14
Show Gist options
  • Save mladenoff/8e927fdce677055c7d47f5b55d4b001c to your computer and use it in GitHub Desktop.
Save mladenoff/8e927fdce677055c7d47f5b55d4b001c to your computer and use it in GitHub Desktop.
Search Lite

API Util

// track_api_util.js

export const fetchSearchResults = search => (
  $.ajax({
    method: 'POST',
    url: '/api/tracks/search',
    data: search,
  })
);

Routes

# routes.rb

Rails.application.routes.draw do

  namespace :api, defaults: { format: :json } do
    post "tracks/search", to: 'tracks#search'
# ...

Controller

# tracks_controller.rb

class Api::TracksController < ApplicationController
# ...
  def search
    @tracks = Track.search(search_params[:term])
    render "api/tracks/index"
end

  private

  def search_params
    params.require(:search).permit(:term)
  end
end

Model

# track.rb
class Track < ApplicationRecord

  belongs_to :artist
  belongs_to :album
# ...
  def self.search(term)
    Track
      .joins(:artist, :album)
      .where(
        "tracks.title ILIKE :term OR artists.name ILIKE :term OR albums.title ILIKE :term",
        term: "%#{term}%"
      )
  end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment