根据条件构建ActiveRecord查询

时间:2017-03-16 17:38:05

标签: ruby-on-rails activerecord

我有以下查询可以正常使用:

temp = Apartment
  .where(rooms: roomsArray)
  .where(area: areasArray)
  .where(price_interval: price_intervalsArray)
  .group(:rooms)
  .count

现在我只想应用.where-queries,如果满足每个条件的某些条件。因此,如果roomsArray为空,我们会跳过整个.where(rooms: roomsArray) - 查询。对于areasArray和price_intervalsArray也是如此。

如何使用条件构建查询?

理想情况下,它看起来像这样:

temp = Apartment
unless roomsArray.empty?
    .where(rooms: key) 
end
unless areasArray.empty?
    .where(area: areasArray)
end
unless price_intervalsArray.empty?
    .where(price_interval: price_intervalsArray)
end
.group(:rooms)
.count

3 个答案:

答案 0 :(得分:0)

你必须正确地链接它们

temp = Apartment.all

if roomsArray.any?
  temp = temp.where(rooms: key) 
end

# or like this with shorter syntax
temp = temp.where(rooms: key) if roomsArray.any?

# and so on with the other conditions
# and then temp will include what you want...

temp

答案 1 :(得分:0)

temp = Apartment.all
temp.where!(rooms: roomsArray) if roomsArray.present?
temp.where!(area: areasArray) if areasArray.present?
temp.where!(price_interval: price_intervalsArray) if price_intervalsArray.present?
temp.group(:rooms).count

P.S。如果接收方为present?或为空,则false会返回nilwhere!修改了关系(查询的包装器)。

答案 2 :(得分:0)

您可以使用此格式。我个人喜欢这种方式。

您可以有条件地在哈希中设置密钥,并将哈希值传递给where

conditions = {}
conditions[:rooms] = roomsArray if roomsArray.present?
conditions[:area] = areasArray if areasArray.present?
conditions[:price_interval] = price_intervalsArray if price_intervalsArray.present?
Apartment.where(conditions).group(:rooms).count