Mongoid查询 - 优化搜索实现

时间:2013-12-30 08:41:31

标签: ruby-on-rails mongodb ruby-on-rails-4 mongoid mongoid3

我正在研究Rails4和Mongoid中的精简搜索。这是我的搜索参数和表格,

enter image description here

我逐件构建了查询:

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

如果我需要在“Hebbal”位置搜索程序“椎间盘切除术”,那么我将如下定义if条件,

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

然后我需要做所有这些组合(4x3x2x1)的搜索,我的精炼搜索!!! 哪个是实现相同的最佳方式。

你如何实现上述情况???

我无法正确处理所有可能的条件,是他们的任何捷径方法!!!

如何实现以下代码:

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

1 个答案:

答案 0 :(得分:1)

你可以这样做:

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)

修改

关于你的上一个代码,因为你这里没有逻辑(所有值的常见想法),你可以使用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