基于属性存在的轨道条件



我想知道是否有更好的方法可以做到这一点:

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

rails 4 是否提供了仅在值存在时才执行条件而不是将其与 NULL 值一起放置的东西?

我不

相信有任何方法可以完全按照你提到的去做。我遇到了相同类型的查询串联。

要清理一点并使其更紧密,您可以使用单行ifunless。我认为这更干净一些,仍然可读。

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

我还更改了第一个查询,以在where中使用 Rails 样式查询而不是 SQL。

最新更新