name_scope 问题导致 will_paginate 出错 - 如何将 group_by 包含在计数中?

发布于 2024-11-25 19:33:18 字数 776 浏览 0 评论 0原文

[rails 2.3.12]named_scope:

named_scope :order_by_price, lambda {{:joins => :variants, :group => "products.id", :order => "MAX(price)"}}

控制台:

1.
> Product.order_by_price.size
=> 21

2. 
> p = Product.order_by_price
> p.size
=> 4

sql查询:

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)

我使用will_paginate进行分页。在本例中,total_entries 值为 21,页数以此为基础,尽管只有 4 个产品...

有什么想法可以让它正常工作吗?

编辑

一般来说,我在调用 Product.count 时必须包含 group_by ...如何?

[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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

我恋#小黄人 2024-12-02 19:33:18

没有答案,但我找到了解决方案。也许对其他人也有用。我只需要重新定义计数,选择​​不同的product_id:

  def self.count(*args)
    super(args, {:select => "(products.id)", :distinct => true})
  end

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文