def keyword
if params[:keyword]
keywords = params[:keyword].split(/[[:blank:]]+/).select(&:present?)
keywords.each do |keyword|
offices = Office.where('name LIKE ? OR address LIKE ? OR near_station LIKE ? OR introduction LIKE ? OR company LIKE ?',"%#{keyword}%", "%# {keyword}%", "%#{keyword}%", "%#{keyword}%", "%#{keyword}%")
end
else
pagy, offices = pagy(Office.all)
pagy_headers_merge(pagy)
end
render json: offices, each_serializer: OfficeIndexSerializer, include: '**'
end
I was wandering around with such a description. The reason is that it is possible to search with one word, but with multiple keywords (for example, with a search method such as "Tokyo Fukuoka", you can only search with the letters Fukuoka.
--I'm writing an iterative process using each statement, but it doesn't seem to work in the first place. ――I'm not sure if the contents of the where clause are correct ...
def keyword
if params[:city_id]
offices = Office.where(city_id: params[:city_id])
elsif params[:keyword]
keywords = params[:keyword].split(/[[:blank:]]+/).select(&:present?)
offices = []
keywords.each do |keyword|
offices += Office.where('name LIKE (?) OR address LIKE (?) OR near_station LIKE (?) OR introduction LIKE (?) OR company LIKE (?)',"%#{keyword}%", "%#{keyword}%", "%#{keyword}%", "%#{keyword}%", "%#{keyword}%")
end
else
pagy, offices = pagy(Office.all)
pagy_headers_merge(pagy)
end
render json: offices
end
The strange thing is that I added ʻoffices = [] ``. An image of making a box to store keywords. Then I added () to
ʻoffice + = Office.where`` and? In the where clause.
As a result, it was possible to establish a search function not only for a single-word keyword search such as "Tokyo" but also for multiple keywords such as "Tokyo Fukuoka Chiba".
Recommended Posts