Close this search box.

Using array_position to Sort ActiveRecord Records By Array


In Ruby on Rails, you may face the issue when you try to use .where with array but your expected result is sorted by your input array. Because in Rails the result of .where is sorted by id in default.

In this blog post, I’m going to share quick tips by using array_position to get your result sorted by input array.

Here is the data we prepared for demonstration of using array_position. A table called fruits with five different of fruit.

#<ActiveRecord::Relation [
  #<Fruit id: 1, name: "Apple", quantity: 20, created_at: "2021-09-12 16:33:55", updated_at: "2021-09-12 16:33:55">,
  #<Fruit id: 2, name: "Orange", quantity: 10, created_at: "2021-09-12 16:34:07", updated_at: "2021-09-12 16:34:07">,
  #<Fruit id: 3, name: "Watermelon", quantity: 30, created_at: "2021-09-12 16:34:32", updated_at: "2021-09-12 16:34:32">,
  #<Fruit id: 4, name: "Banana", quantity: 40, created_at: "2021-09-12 16:34:49", updated_at: "2021-09-12 16:34:49">,
  #<Fruit id: 5, name: "Kiwi Fruit", quantity: 50, created_at: "2021-09-12 16:35:05", updated_at: "2021-09-12 16:35:05">

First, we are using this ruby code to query these three fruits. Banana, Kiwi Fruit and Orange.
Fruit.where(name: ["Banana", "Kiwi Fruit", "Orange"])
and here is the result

#<ActiveRecord::Relation [
  #<Fruit id: 2, name: "Orange", quantity: 10, created_at: "2021-09-12 16:34:07", updated_at: "2021-09-12 16:34:07">,
  #<Fruit id: 4, name: "Banana", quantity: 40, created_at: "2021-09-12 16:34:49", updated_at: "2021-09-12 16:34:49">,
  #<Fruit id: 5, name: "Kiwi Fruit", quantity: 50, created_at: "2021-09-12 16:35:05", updated_at: "2021-09-12 16:35:05">

You can see that even your input array is ["Banana", "Kiwi Fruit", "Orange"] but the result is sorted by ID. Is there a way to sort the result by the input array? You can use array_position. We can just make a smaller change to achieve.

fruits = ["Banana", "Kiwi Fruit", "Orange"]

# { |x| "'#{x}'" }.join(',') used to convert array to string 'Banana', 'Kiwi Fruit', 'Orange'
Fruit.where(name: fruits).order("array_position(ARRAY[#{ { |x| "'#{x}'" }.join(',')}], name::TEXT)")

Here is the ActiveRecord result

#<ActiveRecord::Relation [
  #<Fruit id: 4, name: "Banana", quantity: 40, created_at: "2021-09-12 16:34:49", updated_at: "2021-09-12 16:34:49">,
  #<Fruit id: 5, name: "Kiwi Fruit", quantity: 50, created_at: "2021-09-12 16:35:05", updated_at: "2021-09-12 16:35:05">,
  #<Fruit id: 2, name: "Orange", quantity: 10, created_at: "2021-09-12 16:34:07", updated_at: "2021-09-12 16:34:07">

as you can see you can use array_position to sort the record by array.

What if I’m using MySQL?

you can use field to sort the result

fruits = ["Banana", "Kiwi Fruit", "Orange"]
Fruit.where(name: fruits).order("field(name, #{fruits.join(',')})")

50 thoughts on “Using array_position to Sort ActiveRecord Records By Array”

    Alrighty, in previous articles we figured out the functionality.
    Let’s now take a look at the advantages of such a blockchain system, besides its size.
    The first advantage of the Mina protocol is the high confidentiality of user data.
    Other blockchains, like Ethereum, do blockchain computations.

    REMITANO the largest cryptocurrency exchange in Southeast Asia
    Free RENEC COINS MINING on your phone
    Link Earn RENEC:
    With only 3 steps and 30 seconds a day, you can mine RENEC coin completely free. RENEC coin value can be up to $50/coin

  3. METAMUSK team is launching the first token Airdrop of 500kk METAMUSK (≈2.5 BNB). Get on official website –>

  4. During this period of uncertainty in the crypto market, we need the help of an expert in the form of a financial advisor that specializes in beating the market makers and maximizing profits for clients. Contact Mr Kyle Morgan on whatsapp +12087322211

  5. Howdy an greatly immense much recognized from my side for you. The compelling and obligatory web journal you’ve got composed for us. More regularly than not basic for the journalists and understudies as well. i will be related with you people bunches to start an bewildering web journal like this.
    iPhone Home Button Replace

  6. Presently i have come to on a right goal. I am giving the surety you may be type in a important and graphic data for our perusers yellowstone merchandise . We receive a information & that will be more supportive for us in a future. Trust you may fulfill our perusers by pass on a right data.

  7. Thank you for your post. I have read through several similar topics! However, your article gave me a very special impression, unlike other articles. I hope you continue to have valuable articles like this or more to share with everyone! poppy playtime

  8. Washington Commanders

    You are in the right place at the right moment. Football Club The Washington Commanders Varsity Jacket We offer the perfect outwear for you that will not only keep you warm in the Siberian winds, but will also improve your attractiveness and make your personality spicy and peppery. Furthermore, because of its trendy features, it helps you stand out in a crowd.

  9. infected days

    This is an excellent article! I am very eager to see your rather beneficial information. Other than that, this is a great blog with loads of useful information. Keep up the great work you’re doing here!
    scribbl io

  10. I looked on the internet for Snoop Dogg Clothing in my price range but couldn’t find anything, so a buddy suggested I go on Hit Jacket. I quickly spotted this Snoop Dogg Clothing on Hit Jacket at a fair price and purchased it. It was arrived today, and it is beautifully made with high-quality materials and a perfect design.

  11. Are you looking for a fun online game? Then, Wordle game online is surely the best choice for you. This game will give you six chances to guess a random word. Let’s try to play it with your friends now!

  12. I searched the internet for a ms marvel kamala khan jacket in my price range but came up empty-handed, then a friend recommended Vjackets. I promptly found this ms marvel kamala khan jacket on Vjackets and ordered it for a reasonable price. It came today, and it is exquisitely constructed with high-quality materials and a flawless design.

  13. RSI is a technical analysis tool that calculates the strength of an asset, in this case, bitcoin. When bitcoin rsi reaches a certain point, the asset is considered to be oversold, and therefore likely to go down in price. However, it is not a holy grail in the markets, and you should always remember that RSI does not always provide good signals. However, if you use it correctly, it can help you predict price moves.

  14. The role of a cryptocurrency market making is crucial for the successful operation of a crypto exchange. Market makers are responsible for facilitating tight markets through reduced friction and tight spreads. They also facilitate the availability of crypto assets in the market, making them more attractive to traders. While exchanges act as venues for trade, they are insufficient without market makers to provide the liquidity necessary for tight order books. As a result, they play a vital role in the efficiency of the trading experience and price discovery.

  15. wordle website is the most interesting word search game today, there are 4 to 11 letters hidden in the squares and your main task is to find it to complete a complete and most accurate word as required. demand of this game. You have a maximum of six guesses and if the answer is wrong, you have to wait until the next day to start this game again.

  16. Not only is your site informative, but it’s also really creative. I looked over and gave what you said some thought. I have it bookmarked and plan to review fresh content. Well done for creating such a helpful website.

  17. Approximately 97% of students in the UK say they detest dissertations, according to a survey. However, nobody actually likes writing dissertations. This is because they call for extensive investigation from the pupils. Don’t worry, though, if that applies to you as well. This is so that Dissertations Land can help you with all of your academic problems. With the aid of our Law dissertation Writers, you can easily get great benefits. Additionally, you may simply get top grades for your dissertation.

  18. Java developers are in high demand, so how do you land one of the top jobs? There are a few key things you need to know. The first is what you should know about the job market and where to look. You can also find the latest job openings in your area by checking out websites and job boards. Once you’ve narrowed down your job search to a few top companies, you can start submitting your resume.

  19. Our Assignment Writing Services in UK are our most significant asset, so we give them all of our time, energy, and resources. They need constant oversight from a team of knowledgeable and experienced proofreaders who will check your work several times for each criterion to assure the greatest level of quality.

  20. Thank you so much for your wonderful essay, and best of luck to you in the future. I hope you’ll keep writing in this style. The Star Trek Season 2 Picard Patrick Coat was inspired by the “Star Trek Season 2 Picard Coat” television series and actor Patrick Stewart’s portrayal of the fictional character Jean Luc Picard.

  21. Thetradebuzz is one of the top B2B marketplace to connect with international manufacturers, suppliers, buyers, and importers to trade online via our B2B website for export & import!

Leave a Comment

Your email address will not be published. Required fields are marked *