简体   繁体   中英

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. Hope I'm making sense?

Here is my code below:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM