Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails render as json, include nested attribute and sort

I am trying to render an object as json, including nested attributes and sort them by created_at attribute.

I'm doing this using the code:

format.json  { render :json => @customer, :include => :calls}

How can I sort calls by created_at attribute?

like image 435
silkwormy Avatar asked Aug 07 '11 11:08

silkwormy


1 Answers

If you think how Rails works, calls is just a method that relates to the Call model. There are a few ways you can do this. One is to set the order option on the association. One is to change the default scope of the Call model globally, another creates a new method in the Customer model that returns the calls (useful if you wish to do anything with the calls before encoding.)

Method 1:

class Customer < ActiveRecord::Base
  has_many :calls, :order => "created_at DESC"
end

UPDATE

For rails 4 and above use:

class Customer < ActiveRecord::Base
  has_many :calls, -> { order('created_at DESC') }
end

Method 2 :

class Call < ActiveRecord::Base
  default_scope order("created_at DESC")
end

Method 3:

class Call < ActiveRecord::Base
  scope :recent, order("created_at DESC")
end

class Customer < ActiveRecord::Base
  def recent_calls
    calls.recent
  end
end

Then you can use:

format.json  { render :json => @customer, :methods => :recent_calls}
like image 67
Gazler Avatar answered Sep 19 '22 13:09

Gazler