问题
[rails 2.3.12] named_scope:
named_scope :order_by_price, lambda {{:joins => :variants, :group => "products.id", :order => "MAX(price)"}}
console:
1.
> Product.order_by_price.size
=> 21
2.
> p = Product.order_by_price
> p.size
=> 4
sql queries:
1.
SELECT count(*) AS count_all FROM `products` INNER JOIN `variants` ON variants.product_id = products.id
2.
SELECT `products`.* FROM `products` INNER JOIN `variants` ON variants.product_id = products.id GROUP BY products.id ORDER BY MAX(price)
I use will_paginate for pagination. In this case total_entries value is 21 and number of pages is based on this, although there are only 4 products...
Any ideas how can I get this to work correctly?
EDIT
In general I have to include group_by when calling Product.count... how?
回答1:
No answers, but I found a solution. Maybe it will be useful for someone else too. I just had to redefine count, selecting distinct product_id:
def self.count(*args)
super(args, {:select => "(products.id)", :distinct => true})
end
来源:https://stackoverflow.com/questions/6790295/problem-with-named-scope-causes-error-in-will-paginate-how-to-include-group-by