Rails render as json, include nested attribute and sort
Asked Answered
C

1

19

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?

Chauffer answered 7/8, 2011 at 11:10 Comment(3)
I guess you can define the default sort while defining the relationship. api.rubyonrails.org/classes/ActiveRecord/Associations/…Sabol
@tjameson They are calling the render(:json) method, I think it is safe to refer to it as rendering JSON in this context.Kendry
Sorry to be a grammar nazi, but "render" does not deal exclusively with graphics.Lenka
K
50

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}
Kendry answered 7/8, 2011 at 11:17 Comment(7)
How to put multiple methods I tried :method => :abc, :xyz it's not workingTarton
@iamkdev :method => [:abc, :xyz]Culhert
in Rails 5.0, the :order => 'created_at DESC' doesn't work any more, should use -> { order('created_at DESC') }Continuum
@Gazer I have Rails 4 and :order => 'created_at DESC does not work, and got ArgumentError - Unknown key: :orderSarge
@Sarge Please see the comment above yours.Kendry
@Gazer, I'm confused, Spark was talking about Rails 5Sarge
This is amazing.Lovellalovelock

© 2022 - 2024 — McMap. All rights reserved.