Answer the question
In order to leave comments, you need to log in
How to output data from a model in a certain order in Ruby on Rails?
For example, there is a User
model
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
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])
User.where(id: [1,3,2]).order("case id when 1 then 1 when 3 then 2 when 2 then 3 end")
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question