让列表以不同的方式排序

首先写一个helper方法:

 

  def link_to_order(order)
    link_to(order.capitalize,
      :controller => "spaces",
      :action => "all",
      :params => { "order" => order })
  end

 

页面调用:

 

<%= link_to_order("nickname") %>
<%= link_to_order("password") %>

 

具体实现:

 

  def all
    @order = params[:order] || "id"
    sort_proc = case @order
    when "nickname" then lambda {|r| [r.nickname] }
    when "nickname",
        "password" then lambda {|r| [r.send(@order)]}
    when "password" then lambda {|r| r.password }
    end
    @spaces = Space.find(:all).sort_by &sort_proc
  end

 

你可能感兴趣的:(排序)