[英]Ruby on Rails/will_paginate: Ordering by custom columns
I've got a rather complicated SQL-Query whose results should be paginated and displayed to the user. 我有一个相当复杂的SQL查询,其结果应进行分页并显示给用户。 I don't want to go into details here, but to put it simple I just select all columns of a model, and an additional column , that is used just for sorting purposes. 我不想在这里进行详细说明,但是简单起见,我只选择模型的所有列, 然后选择一个额外的column ,它仅用于排序目的。
Note.select( ['notes.*', "<rather complicated clause> AS 'x'"] ).joins(...)...
After some .join()'s
and a .group()
, I finally call .order()
and .paginate
on the relation. 经过一些.join()'s
和.group()
,我最终在关系上调用.paginate
.order()
和.paginate
。 If I order by any of the model's natural columns everything works fine, if I however order by the "artificial" column x
, rails gives me the error: 如果我按模型的自然列中的任何一个排序,则一切正常,如果我按“人工”列x
排序,则rails会给我错误:
no such column: x
This seems to occur because will_paginate seems to do a COUNT(*)
-statement before getting the actual data, simply to get the amounts of data it has to process. 这似乎是因为will_paginate似乎在获取实际数据之前只是执行COUNT(*)
语句,只是为了获取它必须处理的数据量。 This COUNT(*)
-statement is (of course) generated from the original statement, which includes the ORDER BY x
. 这个COUNT(*)
语句(当然)是从原始语句生成的,该原始语句包括ORDER BY x
。 The problem now is, that will_paginate keeps the ORDER BY
in the statement but simply replaces the column definitions with COUNT(*)
and thus cannot find the column x
. 现在的问题是,will_paginate将ORDER BY
保留在语句中,而只是用COUNT(*)
替换列定义,因此找不到列x
。
Using Rails 3
and will_paginate 3.0.pre2
. 使用Rails 3
和will_paginate 3.0.pre2
。
Is there any way to get around this? 有什么办法可以解决这个问题?
thx for any help 感谢任何帮助
You can disable the initial count query by passing in the value manually: 您可以通过手动传递值来禁用初始计数查询:
total_entries = Note.select(...).joins(...).count
Note.select( ... ).joins(...).group().paginate(:total_entries => total_entries)
The above is not a literal code sample and you may need to tweak your count query to get the correct results for your join. 上面的代码不是文字代码示例,您可能需要调整计数查询以获得正确的联接结果。 This should let you do a straight up complex query on the pagination. 这应该使您可以对分页进行简单的复杂查询。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.