V
V
Vayladion Gognazdiak2018-03-15 20:32:17
Ruby on Rails
Vayladion Gognazdiak, 2018-03-15 20:32:17

How to gracefully perform a single sort in RoR ( AR )?

Evening in joy, seagulls in sweetness.
ENV: ruby ​​2.4.1 + ror 5.1.4 + postgresql
Model available:

create_table "phones", force: :cascade do |t|
    t.integer "id"
    t.string "type"
    t.datetime "created_at"
  end

The type field in the model can take only 3 values: ios, android, wp.
There are (for example) 12 records in the table - 4 of each type, created inconsistently (those. ios, ios, android, wp ... )
It is required to do sorting so that the ios type is displayed first, sorted by created_at, then android is the same by created_at, and wp for dessert.
You can actually solve it like this:
ordering_by_id = []
ordering_by_id << Phone.where(type: 'ios').order(created_at: :desc).select(:id) ....
ordering_by_id << Phone.where(type: 'android').order(created_at: :desc).select(:id) ....
@phones = Phone.where(id: ordering_by_id).order_as_specified(id: ordering_by_id)

But I think there is a more elegant way.
Thanks in advance and plus to you in karma!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Artur Bordenyuk, 2018-03-16
@etspring

Store the type like a rails enum. The field in base will be integer. Specify the desired order in the model.

A
Andrey Andreev, 2018-03-15
@b0nn1e

Theoretically it should work like this

SELECT *
FROM phones
ORDER BY idx(array['ios','android','wp'], phones.type)

But this is not accurate :)
In general, here you need to look at how to do this at the base level, and not at the AR level

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question