开发者

Rails 3: Sorting array through a link in a view

I have an @array and a v开发者_运维百科iew where each array element is listed. Right next to that list I want a link which says "Sort by rank".

I know how to sort an array by a certain attibute

array.sort {| a, b | a[:rank] <=> b[:rank] }

But I don't know what I have to put in the view and controller, so it displays me the sorted array as soon as I click the link.


Generally you create a parameter that re-loads the page with the appropriate filter engaged:

<%= link_to('Sort', :order => 'rank') %>

Then in your controller you have something that re-sorts the list if required:

if (params[:order] == 'rank')
  @array.sort_by!(&:rank)
end

There are plug-ins that will make this easier, plus you should probably be doing the sorting in the database if you have pagination.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜