Rails渲染为json,包括嵌套属性和排序 [英] Rails render as json, include nested attribute and sort
问题描述
我正在尝试将一个对象呈现为json,包括嵌套属性,并按created_at属性对其进行排序.
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}
如何按created_at属性对呼叫进行排序?
How can I sort calls by created_at attribute?
推荐答案
如果您认为Rails的工作原理,则调用只是与Call模型相关的一种方法.有几种方法可以做到这一点.一种是在关联上设置订单选项.
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.)
方法1:
class Customer < ActiveRecord::Base
has_many :calls, :order => "created_at DESC"
end
更新
对于4或以上的滑轨,请使用:
For rails 4 and above use:
class Customer < ActiveRecord::Base
has_many :calls, -> { order('created_at DESC') }
end
方法2:
class Call < ActiveRecord::Base
default_scope order("created_at DESC")
end
方法3:
class Call < ActiveRecord::Base
scope :recent, order("created_at DESC")
end
class Customer < ActiveRecord::Base
def recent_calls
calls.recent
end
end
然后您可以使用:
format.json { render :json => @customer, :methods => :recent_calls}
这篇关于Rails渲染为json,包括嵌套属性和排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!