Question

I am kind of new at rails, currently using version 3.23 and I am trying to enable 'sort' on two columns in my table. I managed to create the links on these column headers and actually got one column working/sorting!But couldnt achieve the same result when I modified my code in the movie controller rb, my code can only work for one column! is:

def index
  @movies = Movie.all.sort_by { |movie| movie.title } 
end

Works perfectly, but when I combine another parameter i.e. release date I get an error!

def index
  @movies = Movie.all.sort_by { |movie| movie.title } then { |release date| release.date}
end

Can someone please help me resolve this issue? I have researched it on google but I've gotten nothing conclusive!. Any help will be most appreciated.

Was it helpful?

Solution

Assuming that you have to sort on title and release_date fields in movies table.

You can perform the sorting at database level itself as below:

In Rails 4.x:

Below will sort all the movie records with title and release_date in ascending order(as default).

def index
  @movies = Movie.order(:title, :release_date)
end

If you want to change the order, you can specify as asc or desc as:

def index
  @movies = Movie.order(title: :asc, release_date: :desc)
end

In Rails 3.x:

def index
  @movies = Movie.all(:order => "title ASC, release_date ASC")
end

If you want to change the order, you can specify as DESC in the above case.

OTHER TIPS

You can order your listing by this

def index
    @movies = Movie.order(title: :asc, release_data: :desc)
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top