Vinny Alfieri Vinny Alfieri - 4 months ago 14
Ruby Question

Advanced Active Record order by using regex

I am trying to query my Order model for all records but I want them ordered in a very specific way.

I want all records that start with

NY
first,
NYN
next, then all remaining records follow.

I think I'm trying to do something like this:

Order.all.order('order_number /^NY/, /^NYN/')


An example of data:



NY-1111111
NYN-1234567
P-000000
P0000000
SS0232131
NYN16151202


The order I want is:

NY-1111111
NYN16151202
NYN-1234567
P0000000
P-000000
SS0232131

Answer

You can do that by ruby sort_by method like this:

orders = Order.all.sort_by{ | order |
    if order.name =~ /^NYN/
        -1;
    elsif order.name =~ /^NY/
        -2;
    else
        0;
    end
}

So if order names are : ["ghi", "NYabc", "jk", "NYNdef"], the order would be: ["NYabc", "NYNdef", "ghi", "jk"] or ["NYabc", "NYNdef", "jk", "ghi"]

You can find the documentation of sort_by here

Update:

Okay, so if you want Active Record as output instead of Array then you can do following:

orders = Order.find( orders.map(&:id) )

Please comment if there is any problem.

Hope it helps : )

Comments