[英]Sorting table with associated columns rails
我正在嘗試使用關聯的列對表格進行排序,以便用戶可以按歌曲名稱,藝術家,專輯,流派和長度對歌曲進行排序。 但是我不確定該怎么做。 現在,我只能按歌曲名稱對歌曲進行排序。
更新
因此,第一列正在工作。 但是我無法對其余的列進行排序,如果我單擊歌曲名稱對其進行排序,它們只能還原為“ asc”或“ dsc”。 希望我有道理?
這是我的代碼如下:
SongsController
def index
@songs = Song.order("#{sort_column} #{sort_direction}").paginate(:page => params[:page], :per_page => 10)
@latest_albums = Album.order('created_at DESC').last(5)
end
private
def sortable_columns
["name", "length", "artist", "album", "genre"]
end
def sort_column
sortable_columns.include?(params[:column]) ? params[:column] : "name"
end
def sort_direction
%w[asc desc].include?(params[:direction]) ? params[:direction] : "desc"
end
end
樂曲助手
def sort_link(column, title = nil)
title ||= column.titleize
direction = column == sort_column && sort_direction == "asc" ? "desc" : "asc"
icon = sort_direction == "asc" ? "fa fa-angle-double-up" : " fa fa-angle-double-down"
icon = column = sort_column ? icon : ""
link_to "#{title}<span class='#{icon}'></span>".html_safe, {column: column, direction: direction}
end
視圖
<thead>
<tr>
<th>#</th>
<th width="10%"></th>
<th><%= sort_link "name", "Song" %></th>
<th><%= sort_link "artist_id", "Artist" %></th>
<th><%= sort_link "album_id" %></th>
<th><%= sort_link "length" %></th>
<th><%= sort_link "genre_id" %></th>
<th></th>
<th></th>
</tr>
</thead>
謝謝!
更改
icon = column = sort_column ? icon : ""
至
icon = column == sort_column ? icon : ""
您需要檢查column
是否等於sort_column
,而您的原始代碼是將 column 等同於sort_column
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.