2016-08-24 84 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'。 –