0

I have a search function with multiple conditions and multiple panels connected together as below

hospitals = Hospital.order(created_at: :desc).group(:id)
hospitals = hospitals.joins(medical_subjects: :sicks).where("(medical_subjects.name LIKE ? OR sicks.name LIKE ?) AND hospitals.name LIKE ?" ,
                                                            "%#{params[:freeword_medical_subject_sick_name].strip}%" ,
                                                            "%#{params[:freeword_medical_subject_sick_name].strip}%" ,
                                                            "%#{params[:freeword_hospital_name].strip}%") if params[:freeword_medical_subject_sick_name].present?
hospitals = hospitals.joins(prefecture: [:cities, :stations]).where("cities.name LIKE ? OR stations.name LIKE ?" ,
                                                                                    "%#{params[:freeword_city_station_name]}%" ,
                                                                                    "%#{params[:freeword_city_station_name].strip}%") if params[:freeword_city_station_name].present?
hospitals = hospitals.where(["hospitals.name LIKE ?" , "%#{params[:freeword_hospital_name].strip}%"]) if params[:freeword_hospital_name]
hospitals = hospitals.where(woman_doctor_existed: params[:woman_doctor_existed]) if params[:woman_doctor_existed].present?
hospitals = hospitals.where(emergency_enabled: params[:emergency_enabled]) if params[:emergency_enabled].present?
hospitals = hospitals.where(checkup_enabled: params[:checkup_enabled]) if params[:checkup_enabled].present?
hospitals = hospitals.where(dpc_enabled: params[:dpc_enabled]) if params[:dpc_enabled].present?
hospitals = hospitals.where(parking_enabled: params[:parking_enabled]) if params[:parking_enabled].present?
hospitals = hospitals.where(card_enabled: params[:card_enabled]) if params[:card_enabled].present?
hospitals = hospitals.where(newest_medicine_enabled: params[:newest_medicine_enabled]) if params[:newest_medicine_enabled].present?
hospitals = hospitals.page(params[:page])
hospitals

but it met some errors when I run rubocop this file

  • Assignment Branch Condition for search size is too high.
  • Cyclomatic CompLexity for search is too high.
  • Method Has too many lines. [14/10]
  • Perceived CompLexity for search is too high

Is there any solution to solve it? Thanks for reading and sorry for my english is not good

kientn
  • 1
  • 1

1 Answers1

0

It's saying that you're doing a lot of stuff in one method. You could try breaking it up into smaller methods. Another idea is to remove some of the duplication. For instance, you're frequently adding a WHERE clause if some param is present. Consider something like this:

%i(woman_doctor_existed emergency_enabled checkup_enabled more...).each do |key|
  hospitals = hospitals.where(key => params[key]) if params.has? key
end
michaeltomer
  • 445
  • 3
  • 7