问题
I'd like to use the rank() function PostgreSQL on one of my columns.
Character.select("*, rank() OVER (ORDER BY points DESC)")
But since I don't have a rank column in my table rails doesn't include it with the query. What would be the correct way to get the rank included in my ActiveRecord object?
回答1:
try this:
Character.find_by_sql("SELECT *, rank() OVER (ORDER BY points DESC) FROM characters")
it should return you Character objects with a rank attribute, as documented here. However, this may not be database-agnostic and tends to get messy if you pass around the objects.
another (expensive) solution is to add a rank column to your table, and have a callback recalculate all records' rank using .order whenever a record is saved or destroyed.
edit :
another idea suitable for single-record queries can ben seen here
来源:https://stackoverflow.com/questions/7506432/postgres-window-function-column-with-rails