E
E
eldar_web2016-07-11 19:05:04
Ruby on Rails
eldar_web, 2016-07-11 19:05:04

How to output data from a model in a certain order in Ruby on Rails?

For example, there is a Usermodel
I make the list in this way: I want it to be output in the order in which I indicated, that is, first the first, then the third and the second during the cycle ( ). But when looping, it is displayed sorted by id, that is, it is displayed in order: 1, 2, 3. How can I solve the problem?
@users = User.where(id: [1,3,2])
@users.eacho do |item|

Answer the question

In order to leave comments, you need to log in

2 answer(s)
C
Chronic 86, 2016-07-12
@chronic86

Oddly enough, the each method by itself doesn't sort anything. The sorting is most likely done by the ORM when you call 'where'. If your data is pulled by id, then try using 'find' or write a SQL query.
Something like that

User.find([1,3,2])
или
User.find_by_id([1,3,2])

You can check if the sort is really happening at the time of the 'where' call by querying irb.
py.sy. In my projects find is faster than where

A
Andrey Demidenko, 2016-07-11
@Dem1

User.where(id: [1,3,2]).order("case id when 1 then 1 when 3 then 2 when 2 then 3 end")

But it's better to create a separate position field

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question