【问题标题】:rails gem will_paginate on top of custom method not working自定义方法之上的rails gem will_paginate不起作用
【发布时间】:2013-10-07 20:33:04
【问题描述】:

在我的控制器中,当我尝试在其上堆叠 will_paginate 时,我的 filter_with_params() 方法在 postgres 中导致语法错误。

在我的控制器中我调用:

@styles = Style.filter_with_params(params).paginate(:page => params[:page], :per_page => 6)

模型方法:

class Style < ActiveRecord::Base

def self.filter_with_params(params)
    scoped = where("styles.item != ''")
    if params[:t]
      scoped = scoped.joins(:tags)
      scoped = scoped.select("distinct styles.*, count(*) AS count")
      scoped = scoped.where(tags: { name: params[:t] })
      scoped = scoped.group('styles.id')
      scoped = scoped.having("count(*) = #{params[:t].size}")
    end
    scoped
end

基本上我的过滤方法是寻找标签,然后我需要在这些结果之上进行分页。有类似经历的人吗?

我在这个应用上使用 Rails 3

这是 postgres 错误

PG::Error: ERROR:  syntax error at or near "distinct" LINE 1: SELECT COUNT(*) AS count_all, distinct styles.*, count(*) AS...
                                  ^
: SELECT COUNT(*) AS count_all, distinct styles.*, count(*) AS count, styles.id AS styles_id FROM "styles" INNER JOIN "tagizations" ON "tagizations"."style_id" = "styles"."id" INNER JOIN "tags" ON "tags"."id" = "tagizations"."tag_id" WHERE "tags"."name" IN ('engagement') AND (styles.polenza_item != '') GROUP BY styles.id HAVING count(*) = 1

【问题讨论】:

  • Style.filter_with_params 方法内的查询中有 SQL 错误。
  • 为什么在每一行中让 scoped 等于不同的范围?您不想连接到作用域变量还是我在这里遗漏了什么?
  • @MarekLipka filter_with_params 方法在我附加分页方法之前不会出错

标签: ruby-on-rails ruby postgresql will-paginate


【解决方案1】:

您的 SQL 有问题。您需要在计数之前说出 distinct 子句('count(*) as count_all')。也就是说,一旦您删除了对 count 函数的第一次调用,它应该可以工作。

SELECT distinct styles.*, count(*) AS count, styles.id AS styles_id FROM "styles" INNER JOIN "tagizations" ON "tagizations"."style_id" = "styles"."id" ...

您可以在 Rails 控制台中测试您的查询:

>> sql = "SELECT distinct styles.*, count(*) AS count, styles.id AS styles_id..."
>> a = ActiveRecord::Base.connection.execute(sql)
>> a[0]

希望这会有所帮助。

【讨论】:

  • 那 SELECT COUNT(*) AS count_all 来自 paginate() 方法。我的查询工作正常,直到我使用 paginate 方法。 Style.filter_with_params(:t => ["tagname"]) 工作正常。我将如何重新排序或让分页在我的方法之上工作?
  • 它实际上看起来只有在我将 放入页面后,分页控件才是查询中断的地方。看起来总记录数是打破它的原因
猜你喜欢
  • 2011-11-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-27
  • 2019-09-08
  • 2014-11-29
  • 1970-01-01
相关资源
最近更新 更多