[Ruby] [Order method] Set the order of data in Rails

less than 1 minute read

Reference target person

  • If you are making an application with Rails but want to sort some data

When you want to sort data under specific circumstances

basic form

Model.order(Column: :DESC)
Model.order("Column DESC")

By default, it is ASC (ascending order), so it can be DESC (descending order).

Actually, get the sorted data group

feed_controller.rb


# Get all data in database
feeds = Feed.order(id: :DESC)

# Get all data of the currently logged in user
feeds = current_user.feeds.order(id: :DESC)

This time, I tried to acquire data called Feed model. The above gets all the data in the database, Below is getting all the data for the currently logged in user.

By doing so, a data group in descending order can be acquired.

When you want to change the default settings and sort

Set the sort order in the model file

models/feed.rb


default_scope -> {order(created_at: :desc)}

This time, I also set the sort order for the data called the Feed model. This notation is a lambda function, which is special.

By doing this, it is possible to set the default settings such that the created dates and times (created_at) are sorted in descending order.