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
710 views
in Technique[技术] by (71.8m points)

sorting - Best way to implement sort asc or desc in rails

Is there an elegant way to implement a sort asc and desc actions in the views/controller in rails?

What I have is the common index.html.erb view that lists all of my data of certain model and I want to add some small buttons (or make the title clickable) to sort the list ascending or descending of that column. I am wondering if there is an elegant and efficient way to do it or should I just add a new controller for every column (or button) I want this action to happen.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Here are two examples that I'm using. The first one with @plans is where I just want to order a decimal from lowest to highest. The other example is a bit more complicated where I want to order user files from newest to oldest. I then used a second variable to group the files by the date created. Both examples where performed in the controllers.

@plans = Plan.order("price")

@files= @user.files.order("id DESC").all
@dates = @files.group_by { |t| t.created_at }

For clickable buttons in your view, check out Ryan Bates's Railscast episode covering this information.

http://railscasts.com/episodes/228-sortable-table-columns


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

...