Files
openfoodnetwork/app/services/search_orders.rb
Pau Perez 116109c63d Make /api/orders N+1 free
With the help of the bullet gem, and since we remove a couple of N+1s
already, remove them all was just a few keystrokes away. This commits
gets us from 42 SQL queries to 17, and 364.5ms to 253.9ms on my machine
where I just have the sample data's orders. As usual, this will have
a much bigger impact in scenarios with more data.
2021-02-23 10:26:12 -08:00

47 lines
1017 B
Ruby

class SearchOrders
attr_reader :orders
def initialize(params, current_user)
@params = params
@current_user = current_user
@orders = fetch_orders
end
private
attr_reader :params, :current_user
def fetch_orders
@search = search_query.
includes(:payments, :subscription, :shipments, :bill_address, :distributor, :order_cycle).
ransack(params[:q])
return paginated_results if using_pagination?
@search.result(distinct: true)
end
def search_query
base_query = ::Permissions::Order.new(current_user).editable_orders
return base_query unless params[:shipping_method_id]
base_query
.joins(shipments: :shipping_rates)
.where(spree_shipping_rates: {
selected: true,
shipping_method_id: params[:shipping_method_id]
})
end
def paginated_results
@search.result(distinct: true)
.page(params[:page])
.per(params[:per_page])
end
def using_pagination?
params[:page]
end
end