I have a Ruby on Rails project I created. It uses Rails for the backend and the frontend.
Months ago I had it so that you could search for hikes by searching a keyword that was in the hike name. The hikes matching the search would then show up on the screen.
However, I recently noticed this isn't working anymore. There isn't really an error showing anywhere though.
However, I've done some digging and noticed with binding.pry that the LIKE query I had in my Hike model is no longer working.
I feel that the method in my Hike model should work as coded like this:
def self.search_by_name(search)
if search
Hike.where("name LIKE ?", "%#{search}%")
end
end
From my prying I've noticed that this method is being hit and search is coming through as an argument correctly. However, doing Hike.where("name LIKE ?", "%#{search}%")
in binding.pry returns an empty array, as shown (not sure if the second line showing "hikes".*
is what it should be showing or not):
pry(Hike)> Hike.where("name LIKE ?", "%#{search}%")
Hike Load (0.7ms) SELECT "hikes".* FROM "hikes" WHERE (name LIKE '%park%')
↳ app/models/hike.rb:18:in `search_by_name'
=> []
I recently switched my db from SQLite to PostgreSQL so perhaps that change is requiring a different syntax to be used in my querying within that above method?
Below is how my HikesController looks, where you can see that if params[:q], which means that if someone typed in a search, I am setting @hikes
equal to the calling of the .search_by_name
method being passed the search term. The .search_by_name
method, as shown above, is returning an empty array when you've searched a word, and I've been searching words that are in specific hike names in my database.
class HikesController < ApplicationController
before_action :require_login
def index
if params[:hike] && params[:hike][:":location"] != "None"
@hikes = Hike.search(params[:hike][:":location"])
elsif params[:q]
@hikes = Hike.search_by_name(params[:q])
else
@hikes = Hike.all
end
end
def require_login
return head(:forbidden) unless session.include? :user_id
end
end
As a reminder, this search functionality was working before. Not sure why it isn't now, but I'm curious if it has something to do with changes that are possibly needed after switching my db from SQLite to PostgreSQL. Any help would be appreciated.
Also, I should note that after migrating from SQLite to PostgreSQL my database does seem to be populated correctly. Doing Hike.all
in the rails console does still give me all of my seeded hikes.
CodePudding user response:
In SQLite, like
is case-insensitive by default. %park%
will match Park
.
In Postgres it is case-sensitive. To make it case-insensitive use ilike
.