问题
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