【问题标题】:Mongoid query - Refine Search ImplementationMongoid 查询 - 优化搜索实现
【发布时间】:2014-01-17 03:13:36
【问题描述】:

我正在使用 Rails4 和 Mongoid 进行优化搜索。这是我的搜索参数和表单,

我逐个构建查询:

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条件,他们有什么捷径吗!!!

如何实现以下代码:

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

【问题讨论】:

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


    【解决方案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
    

    【讨论】:

    • 感谢它对我的帮助很大。这就是我正在寻找的。你能帮我上面的最后一个代码 sn-p 如何像你的查询一样完成!!!
    猜你喜欢
    • 2018-02-23
    • 1970-01-01
    • 1970-01-01
    • 2013-03-16
    • 2016-01-06
    • 2021-08-23
    • 2017-06-17
    相关资源
    最近更新 更多