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"]
# fruits.map { |x| "'#{x}'" }.join(',') used to convert array to string 'Banana', 'Kiwi Fruit', 'Orange'
Fruit.where(name: fruits).order("array_position(ARRAY[#{fruits.map { |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(',')})")
30 thoughts on “Using array_position to Sort ActiveRecord Records By Array”
Some paintings are being sold at the London Exhibition for millions of dollars. This is the first digitized NFT version of Dr. Hans Prinzhorn’s collection – https://opensea.io/collection/hans-prinzhorn
WHAT TO KNOW BEFORE BUYING MINA?
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.
Source: https://cryptoine.com/how-does-mina-work-exactly/
Superb blog!! I dare give a title like this. Visit https://takemycoursesforme.com/ for online educational courses and classes.
Learn Programming free…visit https://www.codeforhunger.com
Perfct
For cryptocurrency farming and staking use unifarm. https://unifarm.co
I swear I don’t get a thing about array positioning. Few minutes before I was thinking of how difficult my subject of marketing is and I need to buy https://dissertationsky.co.uk/tourism-and-hospitality-dissertation-topics/ . But after reading your post; I guess I was just being a cry baby and need to focus a little bit more on my studies.
Cryptocurrency is the best for the world today, but @unifarm stand out in all. http://www.unifarm.co
Cryptocurrency is the best for the world today, but @unifarm stand out in all.
Use this link http://www.unifarm.co
Have you heard of Unifarm? The best coin with staking innovation in cryptocurrency farming. http://www.unifarm.co
FREE MINING COIN ON PHONE
REMITANO the largest cryptocurrency exchange in Southeast Asia
Free RENEC COINS MINING on your phone
Link Earn RENEC: https://bit.ly/3mDpGn7
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
Thank you so much for explaining to us array_position and how we can sort ActiveRecord manually. In this wonderful way, not only will we be able to save time, but we will also be able to bring maturity to our work. https://blogswire.com/narrative-writing-tips-and-rules-you-must-follow/
METAMUSK team is launching the first token Airdrop of 500kk METAMUSK (≈2.5 BNB). Get on official website –> muskmetaverse.me
METAMUSK team is launching the first token Airdrop of 500kk METAMUSK (≈2.5 BNB). Get on official website –> https://muskmetaverse.me
https://t.me/best_airdrop_her
#Airdrop #BTC #bounty #cryptocurrency #BNB #ethereum #trading #binance #crypto_Holder #ايردروب #BSC #TRX #Fx #forex
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
He is trustworthy. Verified ✅
We Introduce Bomber Jackets In United State With Premium Quality Leather Used In Making Leather Jackets https://bomberjackets.us/product/skeleton-woolen-varsity-jacket
Grab Amazing Leather Jacket and Cosplay Jacket from our Store with free shipping world wide and extra gifts like TShirts https://grabjackets.com/product/half-black-half-white-leather-jacket
We Are The Best EIN Service Provider In US. https://einhelp.us
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
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.
The compelling and obligatory web journal you’ve got composed for us.
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
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.
Array is very useful if you were to use it properly but not everybody knows how to us it.
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
This is the first time that I visit here. I found so many exciting matters in this particular blog,
Site : Arkam batman jacket
This is an excellent article!
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.