Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to order included elements in Rails 3

I have a model relationship where today has many tasks

I'm trying to retrieve a user's today object, include the tasks and render them all to Json. All of this was going great until I decided I wanted to order the tasks within the today object because respond_with block is also used for rendering the html page. Is there any way to include the tasks and order them?

I'm trying something like this:

class TodaysController < ApplicationController   respond_to :html, :json   def show     @today = Today.where(:user_id => current_user.id).joins(:tasks).includes(:tasks).order(:priority).first     respond_with @today, :include => :tasks   end end 

This retrieves everything correctly, but does not seem to order the tasks at all.

This is what I used to have (which worked great, but didn't have the ordering):

class TodaysController < ApplicationController   respond_to :html, :json   def show     @today = current_user.today     respond_with @today, :include => :tasks   end end 

I know I can retrieve the data and sort it afterwards like this:

@today = current_user.today @today.tasks.sort!{|a,b| a.priority <=> b.priority } 

This works and will pass my tests, but I was hoping for an ActiveRecord way to solve this.

like image 927
royvandewater Avatar asked Mar 18 '11 04:03

royvandewater


1 Answers

Try this in your Today model:

has_many :tasks, :order => 'priority DESC' 

EDIT: As mentioned in comment below, in Rails 4+, this is now:

has_many :tasks, -> { order(:priority => :desc) } 

(more info here)

like image 154
khelll Avatar answered Sep 20 '22 12:09

khelll