sql - Rails Ransack search to get sum of association with conditions -
sorry if title unclear - not sure how word question.
i using rails 3.2, postgresql, , ruby 1.9.3.
i have 2 models: order, has many items. orders have counter_cache items_count, , items have status. need find items status "in_progress" orders within date range.
i using ransack search form, , @ first fine because wanted orders. needed count of items orders, have done sum of counter_cache on order items_count. need limit sum items in_progress.
@search = order.order("orders.created_at desc").search(params[:q]) # retrieves orders within search params, , # paginates them kaminari @orders = @search.result(distinct: true).page(params[:page]).per(params[:per]) # here use original search again because total # needs exclude estimates, , sum items @items_total = @search.result(distinct: true).where(estimate: false) .sum(:items_count)
so me sum, need sum of items.status='in_progress'
. leaning towards looping through orders have, , manually adding in_progress items, using ruby instead of sql. thought there might better way handle this.
thanks!
you can try this:
@search = order.order("orders.created_at desc").includes(:items).where("items.status = 'in_progress'").search(params[:q])
Comments
Post a Comment