[英]Sorting table with associated columns rails
I'm trying to sort table with associated columns, so user can sort songs by song name, artist, album, genre and length. 我正在尝试使用关联的列对表格进行排序,以便用户可以按歌曲名称,艺术家,专辑,流派和长度对歌曲进行排序。 But I'm not sure how to do it. 但是我不确定该怎么做。 as it is now I can only sort songs by their name. 现在,我只能按歌曲名称对歌曲进行排序。
UPDATE 更新
So the first column is working. 因此,第一列正在工作。 But I can't sort with the rest of the columns, they only can revert to 'asc' or 'dsc' If I clicked on the song name to sort them. 但是我无法对其余的列进行排序,如果我单击歌曲名称对其进行排序,它们只能还原为“ asc”或“ dsc”。 Hope I'm making sense? 希望我有道理?
Here is my code below: 这是我的代码如下:
SongsController 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
SongHelper 乐曲助手
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
View 视图
<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>
Thanks! 谢谢!
Change 更改
icon = column = sort_column ? icon : ""
to 至
icon = column == sort_column ? icon : ""
You need to check if column
is equal to sort_column
, whereas, your original code is equating column to sort_column
您需要检查column
是否等于sort_column
,而您的原始代码是将 column 等同于sort_column
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.