Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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?

share|improve this question
    
I can't believe I didn't think to just add the column to the database. Seems to work as intended as long as rank() is last in the SELECT statement. –  bbck Sep 21 '11 at 23:40

1 Answer 1

up vote 2 down vote accepted

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

share|improve this answer
    
Even find_by_sql doesn't return a rank column in ActiveRecord. I saw the other question you linked but I don't think it will suit my situation. I'm paging the results and that would run a query for every record. The rank() function is the best method I have found I just can't get it working. –  bbck Sep 21 '11 at 23:25
    
are you sure ? i just tried this on a Rails 3.0.9 app over Postgre + Postgis and MRI Ruby 1.9.2-p180, and it works (in the console). If you tried this in the console, the inspect method does not return the attribute so you don't see it, but it's there (you can see it by calling .attributes on an object, or calling rank directly). –  m_x Sep 22 '11 at 0:39
    
Ah yes you're right. I had just dismissed it when I didn't see it. –  bbck Sep 22 '11 at 12:00

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.