2016-09-20 40 views
0

我有這個疑問:如果裏面,其中在軌道上查詢

def self.search(nombre,zona,tipoActividad,fechaInicio,fechaFin,nombreProfesor) 

    where("nombre) iLIKE ? or contenido iLIKE ? or descripcion iLIKE ? ", "%#{nombre}%", "%#{nombre}%","%#{nombre}%") 
     .where("lugar iLIKE ?", "%#{zona}%") 
     .where("tipo_actividad iLIKE ?", "%#{tipoActividad}%") 
     .where(['fecha_inicio >= ?', fechaInicio]) ***if !fechaInicio.blank?*** 
     .where(['fecha_fin <= ?', fechaFin]) ***if !fechaFin.blank?*** 
     .joins(:user).where("users.lastname iLIKE ?", "%#{nombreProfesor}%") 
    end 

我有問題,當我有fecha_fin和fecha_inicio過濾。只有在參數存在的情況下,我才需要對它們進行過濾。我如何重新更改查詢喲確定?

謝謝。

回答

2

您的self.search方法正在構建和返回一系列關係操作。

因此,您需要將邏輯存儲在變量中,根據需要添加到鏈中,然後返回關係。

def self.search(nombre, zona, tipo_actividad, fecha_inicio, fecha_fin, nombre_profesor) 
    relation = where("nombre) iLIKE ? or contenido iLIKE ? or descripcion iLIKE ? ", "%#{nombre}%", "%#{nombre}%","%#{nombre}%") 
      .where("lugar iLIKE ?", "%#{zona}%") 
      .where("tipo_actividad iLIKE ?", "%#{tipo_actividad}%") 

    relation = relation.where('fecha_inicio >= ?', fecha_inicio) if fecha_inicio.present? 
    relation = relation.where('fecha_fin <= ?', fecha_fin) if fecha_fin.present? 

    relation = relation.joins(:user).where("users.lastname iLIKE ?", "%#{nombreProfesor}%") 

    return relation 
end