1

I am searching for records using an IN query likes so:

Event.where("events.id IN (#{events.nil? ? '' : events.collect(&:id).join(',')})")

Which produces output like:

SELECT "events".* FROM "events" WHERE (events.id IN (143,169,139,48,172,146,145,124,111,49,108,18,113,144)) AND (status = 'live') LIMIT 10

However, this is then sorted by update_at by default. I'd like it to sort by the IN part of the query. What I mean is that I'd like this to be the order it returns in:

143,169,139,48,172,146,145,124,111,49,108,18,113,144

Is that possible at all?

I must also note that I can't add a priority column or similar to the table as the "events" part will be dynamically generated.

I've just discovered a very similar question here:

Postgres ORDER BY values in IN list using Rails Active Record

Feel free to mark this one of mine as duplicate

4
  • This question has already been anwsered here : stackoverflow.com/questions/866465/… Commented Jan 9, 2013 at 10:28
  • Use .order("events.id asc") in the end. Commented Jan 9, 2013 at 10:28
  • Ahh... I didn't see this comment. Then mark as duplicate... Commented Jan 9, 2013 at 10:29
  • Not quite a duplicate as this is Rails-specific and I'd like to achieve this with ActiveRecord if possible Commented Jan 9, 2013 at 10:33

2 Answers 2

2

This is Rails, so use Rails' methods for database querying. I believe:

Event.where(:id => events.map(&:id)).order(:id)

is what you're looking for.

If events is already a collection of database records, then just .where(:id => events) will also work.

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

3 Comments

Thanks, I have already thought of something similar but I would prefer to do it with AR if possible.
What do you mean? That is using AR.
You are correct, sorry. I ended up using stackoverflow.com/questions/12012574/…
0

Have you tried order by?

SELECT "events".* FROM "events" 
WHERE (events.id IN (143,169,139,48,172,146,145,124,111,49,108,18,113,144)) 
AND (status = 'live') 
ORDER BY events.id asc
LIMIT 10

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.