Boguz Boguz - 1 month ago 9
jQuery Question

Order content on button click on Rails

I am doing a "Vinyl Record Collection" app using Rails. The goal is for me to learn how to use Ruby on Rails.

I have the main app working. I used

rails g scaffold record artist:string title:string publisher:string tracks:text year:integer
and everything is working fine.
I have also styled it and now it is time to add some nice features... ;)

I would like to add a couple of buttons to order the Record List (index.html.erb) in different ways. One button to see if Alphabetically, on to see it by Record title, on to see it by year,...

But i really have no idea on how to go about it. I have tryed to search in google, but i am not even sure on what to look for. Is it the sort_by? Is it sort? Is it .order? Should i do it using Rails or using jQuery? =/

I think that i could sort something using sort, for instance to order by year:

@records.sort! { |a,b| a.year <=> b.year }


but how do i then display the changes? How do i make it work with a button click?

How do i make the view update according to the button clicked?

I would very much appreciate any hel you can give me.

Thank you!
=)

Answer

i used a lot of the code @max wrote in is answer. Had to change it a little bit to make it work.

Ended up using the following code on my records_controller.rb

def index

    @records = Record.order(:artist)

    if params[:order] == 'artist'
        @records = Record.all.order('artist')
    elsif params[:order] == 'title'
        @records = Record.all.order('title')
    elsif params[:order] == 'year'
        @records = Record.all.order('year')
    else
        @Records = Record.all
    end 

end

maybe this can help someone else some day... ;)