railsでofficesコントローラーのsearchアクションを作成しています。
Ruby
1 def search 2 if params[:city_id] 3 pagy, offices = pagy Office.where(city_id: params[:city_id]) 4 pagy_headers_merge(pagy) 5 elsif params[:keyword] 6 keywords = params[:keyword].split(/[[:blank:]]+/).select(&:present?) 7 pagy, offices = pagy_array([]) 8 pagy_headers_merge(pagy) 9 search_office_from_keyword(keywords) 10 else 11 pagy, offices = pagy(Office.all) 12 pagy_headers_merge(pagy) 13 end 14 render json: offices, each_serializer: OfficeIndexSerializer, include: '**' 15 end 16 17 def search_office_from_keyword(keywords) 18 keywords.each do |keyword| 19 offices += Office.where('name LIKE (?) OR 20 address LIKE (?) OR 21 near_station LIKE (?) OR 22 introduction LIKE (?) OR 23 company LIKE (?)', 24 "%#{keyword}%", 25 "%#{keyword}%", 26 "%#{keyword}%", 27 "%#{keyword}%", 28 "%#{keyword}%") 29 end 30 end
このアクションが長すぎてRuboCopに怒られてしまったため、メソッドの分離を試みたのですがうまくいきません。
NoMethodError (undefined method `+' for nil:NilClass):
上記のようなエラーが出てしまいます。
条件分岐のelsifの部分で、search_office_from_keyword(keywords)というメソッドを呼び出しています。
解決方法をご存知の方、教えてください。宜しくお願い致します。
### 変更したコード
ruby
1 def search 2 if params[:city_id] 3 pagy, offices = pagy Office.where(city_id: params[:city_id]) 4 elsif params[:keyword] 5 keywords = params[:keyword].split(/[[:blank:]]+/).select(&:present?) 6 offices = like_(keywords.shift) 7 keywords.each{ |keyword| offices.or(like_keyword) } 8 else 9 pagy, offices = pagy(Office.all) 10 end 11 pagy_headers_merge(pagy) 12 render json: offices, each_serializer: OfficeIndexSerializer, include: '**' 13 end 14 15 def like_(keyword) 16 Office.where('name LIKE ? OR address LIKE ? OR near_station LIKE ? OR introduction LIKE ? OR company LIKE ?',"%#{keyword}%", "%#{keyword}%", "%#{keyword}%", "%#{keyword}%", "%#{keyword}%") 17 end
エラー
ruby
1api_1 | Started GET "/offices/search?keyword=%E6%9D%B1%E4%BA%AC" for 172.21.0.1 at 2020-09-28 07:08:29 +0000 2api_1 | Processing by OfficesController#search as */* 3api_1 | Parameters: {"keyword"=>"東京"} 4api_1 | Completed 500 Internal Server Error in 2ms (ActiveRecord: 0.0ms | Allocations: 696) 5api_1 | 6api_1 | 7api_1 | 8api_1 | NoMethodError (undefined method `prev' for nil:NilClass): 9api_1 | 10api_1 | app/controllers/offices_controller.rb:27:in `search'
27行目は
ruby
1 pagy_headers_merge(pagy) 2 render json: offices, each_serializer: OfficeIndexSerializer, include: '**' 3 end
上のコードのpagy_headers_merge(pagy)
というコードになります。
回答1件
あなたの回答
tips
プレビュー