Question

I am working on refine search in Rails4 and Mongoid. This is my search params and form,

enter image description here

I built the query piece by piece:

if params[:procedure_id]
  @blood_banks = BloodBank.where(:procedure_id => params[:procedure_id])
end
if params[:location_ids]
  @blood_banks = BloodBank.where(:location_id.in => params[:location_ids])
end
...
if condition
end

If i need to search Procedure "Discectomy" in location "Hebbal" then i nned to define the if condition as follows,

if params[:procedure_id].present? && params[:location_id].present?
...
end

Then i need to do for all such combinations(4x3x2x1) of search, for my refine search!!! Which is the best way to implement the same.

How do you achieve above situation???

I can't right all the possible if conditions, is their any shortcut method!!!

How to achieve below code:

if params[:fees].present?
      if params[:fees] == "300"
        @doctor_clinic = DoctorClinic.where( :consultation_fees => { '$lte' => params[:fees] }).map(&:doctor_id)
        @doctors = Doctor.where(
          { :id.in => @doctor_clinic })
      end
      if params[:fees] == "500"
        @doctor_clinic = DoctorClinic.where( :consultation_fees => { '$gte' => 300, '$lte' => params[:fees] }).map(&:doctor_id)
        @doctors = Doctor.where(
          { :id.in => @doctor_clinic })
      end
      if params[:fees] == "1000"
        @doctor_clinic = DoctorClinic.where( :consultation_fees => { '$gte' => 500, '$lte' => params[:fees] }).map(&:doctor_id)
        @doctors = Doctor.where(
          { :id.in => @doctor_clinic })
      end
      if params[:fees] == "1001"
        @doctor_clinic = DoctorClinic.where( :consultation_fees => { '$gte' => params[:fees] }).map(&:doctor_id)
        @doctors = Doctor.where(
          { :id.in => @doctor_clinic })         
      end
    end
Was it helpful?

Solution

You can do this:

conditions = {}
conditions.merge!(:procedure_id => params[:procedure_id]) if params[:procedure_id]
conditions.merge!(:location_id.in => params[:location_ids]) if params[:location_ids]
...
@blood_banks = BloodBank.where(conditions)

EDIT:

Regarding your last code, since you have no logic here (common idea for all values), you can use case:

condition = case params[:fees]
  when "300"
    { '$lte' => 300 }
  when "500"
    { '$gte' => 300, '$lte' => 500 }
  when "1000"
    { '$gte' => 500, '$lte' => 1000 }
  when "1001"
    { '$gte' => 1001 }
  else
    nil
end

if condition
  @doctor_clinic = DoctorClinic.where( :consultation_fees => condition).map(&:doctor_id)
  @doctors = Doctor.where({ :id.in => @doctor_clinic })
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top