Problem with named_scope causes error in will_paginate - how to include group_by in count?

与世无争的帅哥 提交于 2020-01-04 08:27:11

问题


[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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!