Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typo3/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 基于条件构建ActiveRecord查询_Ruby On Rails_Activerecord - Fatal编程技术网

Ruby on rails 基于条件构建ActiveRecord查询

Ruby on rails 基于条件构建ActiveRecord查询,ruby-on-rails,activerecord,Ruby On Rails,Activerecord,我有一个很好的查询: temp = Apartment .where(rooms: roomsArray) .where(area: areasArray) .where(price_interval: price_intervalsArray) .group(:rooms) .count 现在我只想应用.where查询,前提是每个查询都满足某些条件。因此,如果roomsArray为空,我们将跳过整个。Where Rooms:roomsArray查询。区域数组和价格数组也是

我有一个很好的查询:

temp = Apartment
  .where(rooms: roomsArray)
  .where(area: areasArray)
  .where(price_interval: price_intervalsArray)
  .group(:rooms)
  .count
现在我只想应用.where查询,前提是每个查询都满足某些条件。因此,如果roomsArray为空,我们将跳过整个。Where Rooms:roomsArray查询。区域数组和价格数组也是如此

如何使用条件构建查询

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

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

你必须把它们正确地锁起来

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

附言:现在吗?如果接收器为零或为空,则返回false。哪里修改查询包装器中的关系。

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

您可以有条件地设置散列中的键,并将散列传递到何处

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