Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
208 views
in Technique[技术] by (71.8m points)

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

question from:https://stackoverflow.com/questions/65713940/ruby-on-rails-order-by-two-attributes

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...