Rails: scope using created_at date but not time

Viewed 72

I want to show all orders from a user and sort them by date (without time) and then sort according to status using scopes. The closest way I have found is to do this, but I am wondering if there is a better way of doing it:

Model: order.rb

  ...
  scope :order_by_year, -> {order "EXTRACT('year' FROM created_at) DESC"}
  scope :order_by_month, -> {order "EXTRACT('month' FROM created_at) DESC"}
  scope :order_by_day, -> {order "EXTRACT('day' FROM created_at) DESC"}
  scope :order_by_status, -> {order shipment_status: :asc}

Controller: orders_controller.rb

...
    @orders = @user.orders
                   .order_by_year
                   .order_by_month
                   .order_by_day
                   .order_by_status
1 Answers

You can order by using the date function if it is Postgres database, like

scope :order_by_created_date, -> {order("date(created_at) DESC/ASC") }

Related