2

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!

2
  • You have the result of a query, which is an ActiveRecord Relation. You can sort just like an array. Commented Jun 2, 2015 at 1:06
  • @MarsAtomic Thank you, but I need the sorted result to be an ActiveRecord Relation too. Commented Jun 2, 2015 at 4:22

1 Answer 1

2
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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.