2017-03-16 89 views
0

一个ActiveRecord查询我有以下查询该工程只是罚款:构建基于条件

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

现在,我想如果某些条件得到满足为他们每个人只适用。哪里查询。所以如果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 

回答

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 
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 

附: present?返回false如果接收者是nil或者是空的。 where!修改关系(查询的包装)到位。

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