Rails - column value order (priority column)

I have an array priority = ['HIGH', 'MEDIUM', 'LOW']that is used to set the urgency database column. I would like to get data sorted by priority, although the application Task.order(:urgency)returns the results in alphabetical order (i.e. HIGH, LOW, MEDIUM).

I am using PostgreSQL for a database.

I (obviously) would like them to return from high to low priority. Is there an easy way to implement this, possibly using the position of the values ​​in the array?

+5
source share
4 answers

Simple CASE WHENcan achieve the goal (postgreSQL syntax is used here):

scope :urgency_ordered {
  order(<<-SQL)
    CASE tasks.urgency 
    WHEN 'HIGH' THEN 'a' 
    WHEN 'MEDIUM' THEN 'b' 
    WHEN 'LOW' THEN 'c' 
    ELSE 'z' 
    END ASC, 
    id ASC
  SQL
}

:

Task.urgency_ordered
+10

Rails 4.1+, Active Record ( ) :

class Task < ActiveRecord::Base
  enum priority: [ :high, :medium, :low ] 
  # Or enum priority: { high: 0, medium: 1, low: 2 }

  scope :priority_order, ->{ order(:priority) }
  scope :reverse_priority_order, ->{ order(priority: :desc) }
end

/ , , , . Task.priority_order .

+2

, 2. (Rails 4.2.1)

:

class Task < ActiveRecord::Base
    enum priority: { high: 0, medium: 1, low: 2 }
    scope :priority_order, order(:priority)
end

: The scope body needs to be callable.

.

scope :priority_order, -> {
    order(:priority)
}

Proc Lambda.

:)

, , , .

+2

, , : MySQL (, Postgres), , , . SQL-, .

ApplicationRecord :

class Task < ActiveRecord::Base
  scope :order_by_field, ->(field, values) {
    order(sanitize_sql_for_order(["field(#{field}, ?)", values]))
  }
end

:

tasks.ordered_by_field(:priority, ["high", "medium", "low"])
+1

Source: https://habr.com/ru/post/1583795/


All Articles