0

Add `ActiveRecord::QueryMethods#in_order_of`. by kddnewton · Pull Request #42061...

 2 years ago
source link: https://github.com/rails/rails/pull/42061
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Copy link

Contributor

kddnewton commented on Apr 23

Summary

This allows you to specify an explicit order that you'd like records
returned in based on a SQL expression. By default, this will be accomplished
using a case statement, as in:

Post.in_order_of(:id, [3, 5, 1])

will generate the SQL:

SELECT "posts".* FROM "posts" ORDER BY CASE "posts"."id" WHEN 3 THEN 1 WHEN 5 THEN 2 WHEN 1 THEN 3 ELSE 4 END ASC

However, because this functionality is built into MySQL in the form of the
FIELD function, that connection adapter will generate the following SQL
instead:

SELECT "posts".* FROM "posts" ORDER BY FIELD("posts"."id", 1, 5, 3) DESC

This work largely inspired by the new addition to Enumerable here: #41333. cc @dhh


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK