renatojf
renatojf

Reputation: 744

rails conditions based on attributes presence

I was wondering if there's a better way to do this:

def conditions(obj)
  if self.setor.present?
    obj = obj.joins(:negocios_setores).where("setor_id = ?", self.setor.id)
  end

  if self.uf.present?
    obj = obj.joins(localizacao: [:uf]).where("uf_id = ?", self.uf_id)
  end

  if self.municipio.present?
    obj = obj.joins(localizacao: [:municipio]).where("municipio_id = ?", self.municipio_id)
  end

  if !self.lucro_liquido_min.to_f.zero?
    obj = obj.where("lucro_liquido_anual BETWEEN ? and ?", self.lucro_liquido_min, self.lucro_liquido_max)
  end

  if !self.faturamento_min.to_f.zero?
    obj = obj.where("faturamento_bruto_anual BETWEEN ? and ?", self.faturamento_min, self.faturamento_max)
  end

  if !self.valor_min.to_f.zero?
    obj = obj.where("valor BETWEEN ? and ?", self.valor_min, self.valor_max)
  end

  obj
end

Does rails 4 provide something to only do the condition if the value is present instead of placing it with a NULL value?

Upvotes: 0

Views: 33

Answers (1)

James Klein
James Klein

Reputation: 612

I don't believe that there is any way to do exactly what you mentioned. I've run into the same type of concatenation of queries.

To clean up a bit and make this tighter, you can use one-line if and unless. I think this is a bit cleaner and still readable.

def conditions(obj)  
  obj = obj.joins(:negocios_setores).where(setor: setor) if setor.present?
  obj = obj.joins(localizacao: [:uf]).where("uf_id = ?", uf_id) if uf.present?
  obj = obj.joins(localizacao: [:municipio]).where("municipio_id = ?", municipio_id) if municipio.present?
  obj = obj.where("lucro_liquido_anual BETWEEN ? and ?", lucro_liquido_min, lucro_liquido_max) unless lucro_liquido_min.to_f.zero?
  obj = obj.where("faturamento_bruto_anual BETWEEN ? and ?", faturamento_min, faturamento_max) unless faturamento_min.to_f.zero?
  obj = obj.where("valor BETWEEN ? and ?", valor_min, valor_max) unless valor_min.to_f.zero?
  obj
end

I also changed the first query to use Rails style queries rather than SQL in the where.

Upvotes: 1

Related Questions