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