Home>

I want to get Office with the corresponding data when multiple words are entered in params [: keyword].
Currently, when you enter one word "Tokyo", you can display Office, but if you enter multiple words "Tokyo Fukuoka", an error will occur.

def search
    if params [: city_id]
      pagy, offices = pagy Office.where (city_id: params [: city_id])
    elsif params [: keyword]
      keywords = params [: keywords] .split (/ [[: blank:]] + /). select (&: present?)
      relation = like_ (keywords.shift)
      keywords.each {| keyword | relation.or (like_keyword)}
      pagy, offices = pagy relation
    else else
      pagy, offices = pagy (Office.all)
    end
    pagy_headers_merge (pagy)
    render json: offices, each_serializer: OfficeIndexSerializer, include:'**'
  end
  def like_ (keyword)
    Office.where ('name LIKE? OR address LIKE? OR near_station LIKE? OR introduction LIKE? OR company LIKE?', "% # {Keyword}%", "% # {keyword}%", "% # {keyword} % ","% # {keyword}% ","% # {keyword}% ")
  end
api_1 | Started GET "/ offices/search? Keyword =% E6% 9D% B1% E4% BA% AC% E3% 80% 80% E7% A6% 8F" for 172.21.0.1 at 2020-09-29 01:54 : 46 +0000
api_1 | Processing by OfficesController # search as */*
api_1 | Parameters: {"keyword" =>"Tokyo Fuku"}
api_1 | Completed 500 Internal Server Error in 156ms (ActiveRecord: 0.0ms | Allocations: 76554)
api_1 |
api_1 |
api_1 |
api_1 | NameError (undefined local variable or method `like_keyword'for #<OfficesController: 0x00007f7de8024578>
api_1 | Did you mean? Keyword):
api_1 |
api_1 | app/controllers/offices_controller.rb: 23: in `block in search'
api_1 | app/controllers/offices_controller.rb: 23: in `each'
api_1 | app/controllers/offices_controller.rb: 23: in `search'
  • Answer # 1

    Office.where ('name LIKE (?) OR
                                    address LIKE (?) OR
                                    near_station LIKE (?) OR
                                    introduction LIKE (?) OR
                                    company LIKE (?)',
                                         "% # {keyword}%",
                                         "% # {keyword}%",
                                         "% # {keyword}%",
                                         "% # {keyword}%",
                                         "% # {keyword}%")