我的应用中有搜索功能,其工作原理如下
现在我们正在实现如下,但我假设当参数增加超过5-7时,组合数量也会增加if-else-elseif语句的数量。
#refine search
@search = params[:search]
if params[:city].present? && params[:location_ids].present? && params[:search].blank?
@blood_banks = BloodBank.where(
{ :city_id => "#{@city}" }).where(
{ :location_id.in => params[:location_ids] })
elsif params[:search].present? && params[:location_ids].blank?
@blood_banks = BloodBank.where(
{ :bb_name => /#@search/i })
elsif params[:search].present? && params[:city].present? && params[:location_ids].present?
@blood_banks = BloodBank.where(
{ :city_id => "#{@city}" }).where(
{ :location_id.in => params[:location_ids] }).where(
{ :bb_name => /#@search/i })
end
这是实现相同目标的最佳方法。
如何实现以下代码,
if params[:gender].present?
if params[:gender] == "male"
@doctors = Doctor.where( :gender => "Male")
end
if params[:gender] == "female"
@doctors = Doctor.where( :gender => "Female")
end
if params[:gender] == "any"
@doctors = Doctor.where( :gender => "Male") || Doctor.where( :gender => "Female")
end
end
答案 0 :(得分:1)
Mongoid的where
返回Mongoid::Criteria
,Mongoid::Criteria
通过返回另一个where
来回复Mongoid::Criteria
。这意味着您可以逐个构建查询:
@blood_banks = BloodBank.all
if params[:city].present?
@blood_banks = @blood_banks.where(:city_id => params[:city])
end
if params[:location_ids].present?
@blood_banks = @blood_banks.where(:location_id.in => params[:location_ids])
end
...
就第二部分而言,如果您正在搜索任何性别,那么只需将其完全删除,那么您可以执行以下操作:
@doctors = Doctor.all
genders = { 'male' => 'Male', 'female' => 'Female' }
if genders.has_key? params[:gender]
@doctors = @doctors.where(:gender => genders[params[:gender]]
end
搜索任何性别都是相同的,不会过滤性别,因此nil
和'all'
案例是相同的。然后,您可以使用简单的查找表处理输入和:gender
值。