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?
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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With