Search code examples
ruby-on-railsruby-on-rails-4attributessql-order-byassociations

Ruby on rails order_by two attributes


I have a table and in this table i need the finished attribute if its null to be first but at the same time i want the due date to be ordered asc

def all_cases
    @cases=Case.order("finished ASC NULLS FIRST").order(due_date: :asc).paginate(page: params[:page], per_page: 20) 

    if params[:search]
      @search_term = params[:search]
      @cases = Case.order("finished ASC NULLS FIRST").order(due_date: :asc).casesearch_by(@search_term).paginate(page: params[:page], per_page: 20) 
    else
      @cases = Case.order("finished ASC NULLS FIRST").order(due_date: :asc).order(sort_columnn + " " + sort_direction).paginate(page: params[:page], per_page: 20) 
    end
  end

This code added the the finished nulls to be first but not sorted the due date

thanks in advance


Solution

  • Depends on what you want
    Case.order("finished IS NOT NULL").order(due_date: :asc)
    this line of code will ordered by due_date first than ordered by finished attribute,
    so in front of the records you get will be record which finished is null.

    Case.order(due_date: :asc).order("finished IS NOT NULL")
    this line of code will ordered by finished attribute first than ordered by due_date,
    so in front of the records you get will be record which due date is smaller.