2016-08-24 88 views
1

场景:有一个排序按钮,当用户点击它时,列表将按name排序(排序前为created_at)。通过点击按钮导航排序元素

我得到了一个问题是,我做了排序代码的红宝石,但我怎么知道当用户点击按钮?

例如:

<button id = "sort_btn">Sort by name!</button> 
... 

<%# before_sort is origin array %> 
<% sort_arr = Array.new(before_sort) %> 
<%# x[1] is the name attribute %> 
<% sort_arr.sort_by!{|x| x[1]} %> 
<%# if click sort button %> 
<% sort_arr.each do |section_layer1| %> 
<%# if did't click sort button or click twice sort button %> 
<% before_sort.each do |section_layer1|> 
    <%= render :partial => 'list', :locals => {:section => section_layer1 }%> 
<% end %> 

我认为我可能会使用Javascript功能来删除发源显示和用户点击排序按钮后,再次呈现局部视图。

回答

1

Javascript!您可以点击手动添加GET参数:

$(".sort_btn").on('click',function(){ 
    if (url.indexOf('?') > -1){ 
    url += "&sort=sort"; 
    }else{ 
    url += "?sort=sort"; 
    } 
    } 

    window.location.href = url; 

    }); 

然后,如果该参数存在,打印排序表:

<%- if params[:sort].present? %> 
    -- print sorted table -- 
<%- else %> 
    -- not sorted -- 
<% end %> 
+1

最后,我选择用'的link_to +远程TRUE'然后呈现'respond_to js.erb'。 –