A
A
aaltw2021-08-17 09:48:18
Ruby on Rails
aaltw, 2021-08-17 09:48:18

How to get records from database in where order?

There is an array with an id: Records are selected from the database using it: But they are retrieved in the order in which they are in the database. How to preserve the order that is passed in where? Those:
ids = ["4", "1", "3", "2"]
@users = User.where(id: ids)


# Получаю сейчас
User.where(id: ids) # User1, User2, User3, User4

# Хочу получить
User.where(id: ids) # User4, User1, User3, User2

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vayladion Gognazdiak, 2021-08-19
@etspring

Learn ruby ​​and use sort_by

User.where(id: [2,3,1]).sort_by { |user| [2,3,1].index(user.id) }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question