Lei Zhao
Lei Zhao

Reputation: 442

Ruby on Rails / Active Record: Custom Sorting Order

I have a query that can be sorted by date or name.

I also have a URL parameter which is the ID of a specific record. I need to move this record to the top of the list, but keep the rest unchanged.

For example:

if param = 2, then return [2, 1, 3, 4, 5, 6, 7, 8]

if param = 5, then return [5, 1, 2, 3, 4, 6, 7, 8]

if param = 7, then return [7, 1, 2, 3, 4, 5, 6, 8]

... etc.

I know how to do it with an array, but can I do it with Active Record too? Because I need to do pagination etc. after that.

Thanks!

Upvotes: 2

Views: 1020

Answers (1)

smathy
smathy

Reputation: 27961

Foo.order "id = #{param[:param].to_i} desc", :name

I used the .to_i just as a very simple way to ensure this parameter is clean, make sure you do that however you need to so that you're not leaving yourself open to SQL injection.

Upvotes: 2

Related Questions