2014-12-07 48 views
0

我爲項目的待辦事項列表應用程序創建了此表。我想創建按鈕,按表,客戶端,完成了什麼,什麼不是。我不知道如何去了解它..如何創建按鈕來按特定屬性對錶格進行排序?我使用Ruby on Rails

下面是表的代碼:

<table> 
    <thead> 
    <tr id="headers"> 
     <th>Title</th> 
     <th>Client</th> 
     <th>Description</th> 
     <th>Hours</th> 
     <th>Done</th> 
     <th colspan="3"></th> 
    </tr> 
    </thead> 


    <tbody class="col-md-2" id="listItems"> 
    <% @projects.each do |project| %> 
     <tr id="table"> 
     <td><%= project.title %></td> 
     <td><%= project.client %></td> 
     <td><%= project.description %></td> 
     <td><%= project.hours %></td> 
     <td><%= project.done %></td> 

     <td><%= link_to " #{image_tag('show.png')}".html_safe, project, id:'showButton' %></td> 


     <td><%= link_to " #{image_tag('edit.png')}".html_safe, edit_project_path(project),  id:'editButton' %></td> 

     <td><%= link_to " #{image_tag('destroy.png')}".html_safe, project, id:'destroyButton', method: :delete, data: { confirm: 'Are you sure?' } %></td> 

     </tr> 
    <% end %> 
    </tbody> 
</table> 
+0

我聽說datatables(jquery插件)可以做這樣的事情。 – 2014-12-07 07:05:02

+0

您可以使用Sergio建議的插件來做到這一點,或者您可以在Rails中做到這一點(每次單擊表格標題時都會向您的控制器發出額外請求)。你有偏好嗎? – 2014-12-07 07:16:30

+0

@JackZelig我想在Rails中完成它,我想要有一個4個按鈕:按客戶端A-Z排序,按客戶端Z-A排序,按完成 - 未完成排序,然後按最新(正常列表)排序。如果可能的話!謝謝 – GraphicMac 2014-12-07 07:31:25

回答

0

有一個偉大的RailsCast解釋如何做到這一點:#228 Sortable Table Columns

然而,由於答案簡單地鏈接到一個解決方案都皺起了眉頭,這裏是如何實現這個在你的情況下(代碼借來RailsCast情節嚴重):

首先,創建一個輔助方法。它應該有兩個參數。第一個參數是列名,第二個參數是列標題文本,如果這與列名不同。第二個參數是可選的。

/app/helpers/application_helper.rb 
module ApplicationHelper 
    def sortable(column, title = nil) 
    title ||= column.titleize 
    direction = (column == sort_column && sort_direction == "asc") ? "desc" : "asc" 
    link_to title, :sort => column, :direction => direction 
    end 
end 

改變你的index.html.erb像這樣:

/app/controllers/projects_controller.rb 
<tr id="headers"> 
    <th>Title</th> 
    <th><%= sortable "client" %></th> 
    <th>Description</th> 
    <th>Hours</th> 
    <th>Done</th> 
    <th colspan="3"></th> 
</tr> 

在這裏,我只是執行它的客戶端柱。

在項目控制器的索引動作,你這樣做:

helper_method :sort_column, :sort_direction 
def index 
    @projects = Project.order(sort_column + ' ' + sort_direction) 
end 

private 
def sort_column 
    Project.column_names.include?(params[:sort]) ? params[:sort] : "client" 
end 

def sort_direction 
    %w[asc desc].include?(params[:direction]) ? params[:direction] : "asc" 
end 

採用helper_method使其可用於ApplicationHelper兩個sort_方法,使他們能夠在排序助手使用。

這兩個sort_方法可防止SQL注入,並用於設置合理的默認值。

就是這樣。您的客戶專欄現在可以排序。

+0

I把所有這些代碼放入,我收到一個錯誤,說:「在ProjectsController#索引中的SyntaxError,意外的輸入結束,期待keyword_end」 – GraphicMac 2014-12-07 17:14:51

+0

然後你錯過了'結束'等。 – 2014-12-07 18:33:53

相關問題