Search code examples
ruby-on-railsrubyconditional-statementsrecords

How use order by condition


Is it possible to sort the data on a condition?

For example, figuratively, .order( "expiration_date <?", Time.current, :desc )


Solution

  • The ORDER BY keyword is used to sort the result-set by one or more columns. The ORDER BY keyword sorts the records in ascending order by default. To sort the records in a descending order, you can use the DESC keyword.

    you can sort by using something like :-

    sorted = @records.sort_by &:created_at
    

    or try where by first getting the resultset and then sorting it:-

    @records.where( "expiration_date <?", Time.current).order( :created_at, :desc )
    

    Moreover you can paginate easily;-

    @records.paginate(:page => params[:page], :per_page => 15)#.order(" created_at ASC")