rails gem will_paginate在自定义方法无效的基础上

时间:2013-10-07 20:33:04

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

在我的控制器中,当我尝试在其上面堆叠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

1 个答案:

答案 0 :(得分:1)

你的SQL有问题。你需要在count之前说明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]

希望这有帮助。