如何减少数据库查询,值得吗?

时间:2015-01-23 05:33:22

标签: ruby-on-rails ruby ruby-on-rails-4 query-optimization

我目前有一个应用程序,列出从一个位置到另一个位置的航班,其价格和其他信息。我已经通过下拉列表实现了搜索,因此它仅显示从特定位置到特定位置或从某个位置到某个位置的航班,具体取决于用户搜索的方式。

def index
  @flights = Flight.all

  @flights_source = @flights.select('DISTINCT source') #this line is used for options_from_collection_for_select in view
  @flights_destination = @flights.select('DISTINCT destination') #this line is used for options_from_collection_for_select in view

  if params[:leaving_from].present? && params[:going_to].blank?

     @flights = Flight.where(:source => params[:leaving_from])

  elsif params[:going_to].present? && params[:leaving_from].blank?
     @flights = Flight.where(:destination => params[:going_to]) 

  elsif params[:leaving_from].present? && params[:going_to].present?
     @flights = Flight.where(:source => params[:leaving_from]).where(:destination => params[:going_to])     

  end 


end

问题是每次我想添加另一个搜索参数时,例如价格,它将是另一个查询。有没有办法获取Flight.all并在结果中搜索并创建一个只包含与搜索词匹配的记录的新哈希或数组,而不是使用select DISTINCT进行新查询。

我能想出的最接近的事情是以某种方式将Flight.all的结果转换为数组[hash]并使用它获取不同源和目标的结果。但不知道该怎么做。

最后是否值得这样做以减少数据库查询的数量?

这些是当前的查询:

Flight Load (1.4ms)  SELECT "flights".* FROM "flights"
User Load (1.3ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1  ORDER BY "users"."id" ASC LIMIT 1  [["id", 2]]
Flight Load (1.4ms)  SELECT DISTINCT source FROM "flights"
Flight Load (0.8ms)  SELECT DISTINCT destination FROM "flights"

修改

我将select distinct更改为

@flights_source = @flights.uniq.pluck(:source)
@flights_destination = @flights.uniq.pluck(:destination)

在视图中使用options_for_select而不是options_from_collection_for_select。但问题仍然存在,我认为这意味着我尽可能地消灭了我们,但不确定。

(0.8ms)  SELECT DISTINCT "flights"."source" FROM "flights"
(0.6ms)  SELECT DISTINCT "flights"."destination" FROM "flights"
Request Load (1.3ms)  SELECT "requests".* FROM "requests"
Flight Load (1.0ms)  SELECT "flights".* FROM "flights"
User Load (0.5ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1  ORDER BY "users"."id" ASC LIMIT 1  [["id", 2]]

0 个答案:

没有答案