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

sil*_*rmy 13 json ruby-on-rails

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

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

format.json  { render :json => @customer, :include => :calls}
Run Code Online (Sandbox Code Playgroud)

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

Gaz*_*ler 42

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

方法1:

class Customer < ActiveRecord::Base
  has_many :calls, :order => "created_at DESC"
end
Run Code Online (Sandbox Code Playgroud)

UPDATE

对于导轨4及以上使用:

class Customer < ActiveRecord::Base
  has_many :calls, -> { order('created_at DESC') }
end
Run Code Online (Sandbox Code Playgroud)

方法2:

class Call < ActiveRecord::Base
  default_scope order("created_at DESC")
end
Run Code Online (Sandbox Code Playgroud)

方法3:

class Call < ActiveRecord::Base
  scope :recent, order("created_at DESC")
end

class Customer < ActiveRecord::Base
  def recent_calls
    calls.recent
  end
end
Run Code Online (Sandbox Code Playgroud)

然后你可以使用:

format.json  { render :json => @customer, :methods => :recent_calls}
Run Code Online (Sandbox Code Playgroud)

  • 在 Rails 5.0 中, `:order =&gt; 'created_at DESC'` 不再起作用,应该使用 `-&gt; { order('created_at DESC') }` (2认同)