Reputation: 1982
Sorry if the title is unclear - I am not really sure how to word this question.
I am using rails 3.2, postgresql, and ruby 1.9.3.
I have two models: Order, which has many Items. Orders have a counter_cache for items_count, and items have a status. I need to find items with status "in_progress" for orders within a date range.
I currently am using Ransack for my search form, and at first it was fine because I mainly just wanted the orders. Then I needed to get the count of the items for the orders, which I have done with a sum of the counter_cache on order for items_count. But now I need to limit that sum to only items which are in_progress.
@search = Order.order("orders.created_at desc").search(params[:q])
# This retrieves all orders within the search params, and
# paginates them with kaminari
@orders = @search.result(distinct: true).page(params[:page]).per(params[:per])
# Here is use the original search again because my total
# needs to exclude estimates, and then sum the items
@items_total = @search.result(distinct: true).where(estimate: false)
.sum(:items_count)
So this will get me the sum, but I need a sum of just items.status='in_progress'
. I am leaning towards just looping through the orders I already have, and manually adding up in_progress items, using Ruby instead of SQL. But I thought there might be a better way to handle this.
Thanks!
Upvotes: 0
Views: 1536
Reputation: 1555
You can try this:
@search = Order.order("orders.created_at desc").includes(:items).where("items.status = 'in_progress'").search(params[:q])
Upvotes: 1