Rails render as json, include nested attribute and sort

后端 未结 1 853
无人及你
无人及你 2020-12-13 15:34

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.js         


        
相关标签:
1条回答
  • 2020-12-13 16:19

    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}
    
    0 讨论(0)
提交回复
热议问题