2017-03-16 82 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