Ruby on Rails/will_paginate: Ordering by custom columns

限于喜欢 提交于 2019-12-24 06:45:55

问题


I've got a rather complicated SQL-Query whose results should be paginated and displayed to the user. 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.

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. 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:

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. This COUNT(*)-statement is (of course) generated from the original statement, which includes the 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.

Using Rails 3 and will_paginate 3.0.pre2.

Is there any way to get around this?

thx for any help


回答1:


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.



来源:https://stackoverflow.com/questions/7283724/ruby-on-rails-will-paginate-ordering-by-custom-columns

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