Simple Rails search API
April 12, 2021
A simple search API that would allow a Frontend to update results as a user types. This example will search for schools.
First, add a search method to the School model
def self.search(name)
where('name LIKE ?', "%#{name}%")
end
Next, add a search method to the Schools Controller
# GET /schools/search?name
def search
@schools = School.search(params[:name])
render json: @schools, status: :ok
end
Last, add the /search to the route
resources :schools do
collection do
get 'search'
end
end
Now search using a full name of a school: /schools/search?name=Test University
Or a partial name: /schools/search?name=Test U