基于属性存在的rails条件

时间:2016-02-24 19:31:54

标签: ruby-on-rails ruby-on-rails-4.2

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

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

如果存在值而不是将值设置为NULL值,rails 4是否只提供了一些条件?

1 个答案:

答案 0 :(得分:1)

我不相信有任何办法可以完全按照你提到的那样做。我遇到了相同类型的查询连接。

要清理一下并使其变得更紧,您可以使用单行unlessdef 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

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

相关问题