Reputation: 37
i have this query:
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
I have the problem when i have to filter by fecha_fin and fecha_inicio. i need to filter by them only if the parameters are present. How can I re-change the query yo be ok?
Thanks.
Upvotes: 0
Views: 1387
Reputation: 18090
Your self.search
method is building and returning a chain of relation operations.
So you'll need to store the logic in a variable, add to the chain as needed, and then return the relation.
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
Upvotes: 2