Search code examples
ruby-on-railspostgresqlactiverecordspree

ActiveRecord::StatementInvalid error trying to render spree collection


I'm trying to show product related accessories ranked by best selling in my spree store using this:

Spree::Product.class_eval do
  def best_selling_accessories
    accessories.active.select("spree_products.*, SUM(spree_line_items.quantity) AS total_qty, spree_line_items.variant_id").
    joins(:line_items).joins("INNER JOIN spree_orders ON spree_orders.id = spree_line_items.order_id").
    where("spree_orders.state = 'complete'").
    group("spree_line_items.variant_id, spree_products.id").
    order("total_qty DESC")
  end
end

In my controller I'm doing:

@products = @spree_product.best_selling_accessories

When I try to render the view though I get:

PG::UndefinedColumn: ERROR: column "total_qty" does not exist LINE 1: ...line_items.variant_id, spree_products.id ORDER BY total_qty

If I use the better errors shell and manual run the partial render:

render "spree/shared/products", products: @products

It returns the correct html.

Map also returns the correct results from the better errors shell:

>> @products.map { |p| p.total_qty }
=> [14, 10, 7, 7, 4, 3, 3, 3, 3, 3, 1, 1, 1]

So I'm wondering, if it renders correctly in the better errors shell and returns all the correct products when I ask for @products, why does activerecord throw that error?


Solution

  • I just needed to call to_a on the result.

    I'm still confused as to why I can manually run all the commands and they return the correct result though.