Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
704 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 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...