Postgres window function column with Rails

亡梦爱人 提交于 2019-12-23 12:24:41

问题


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

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