Rails呈现为json,包括嵌套属性和排序

时间:2011-08-07 11:10:57

标签: ruby-on-rails json

我试图将对象渲染为json,包括嵌套属性,并按created_at属性对它们进行排序。

我正在使用代码执行此操作:

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

如何按created_at属性对调用进行排序?

1 个答案:

答案 0 :(得分:41)

如果您认为Rails如何工作,则调用只是一种与Call模型相关的方法。有几种方法可以做到这一点。一种是在关联上设置订单选项。一种是全局更改Call模型的默认范围,另一种是在Customer模型中创建一个返回调用的新方法(如果您希望在编码之前对调用执行任何操作,则非常有用。)

方法1:

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

<强>更新

对于导轨4及以上使用:

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}