How can I create a query with alternate sorting in Rails 5?

Asked

Viewed 31 times

0

I have the following formatting in my database

Products
- Name
- Id Loja

with the following records


Product 1 - Shop 1
Product 2 - Shop 1
Product 3 - Shop 3
Product 4 - Shop 1
Product 5 - Store 2
Product 6 - Shop 2
Product 7 - Shop 1
Product 8 - Shop 1
Product 9 - Shop 3
Product 10- Shop 3


I want to make a query where I bring the result by alternating the "Store Id", something that was in the following format:


Product 1 - Shop 1
Product 5 - Store 2
Product 3 - Shop 3
Product 2 - Shop 1
Product 6 - Shop 2
Product 9 - Shop 3
Product 4 - Shop 1
Product 10- Shop 3
Product 7 - Shop 1
Product 8 - Shop 1

This listing will be paginated yet.

1 answer

0

Just use the "order" method your model already inherits from Activerecord:

Produto.order("loja_id asc, nome asc")
  • Thanks for the reply Orlando, but this won’t help me, because I need the result of the query to be alternated by the "Store ID", using the order as you mentioned, it may only come products from the same store in sequence.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.