【问题标题】:Order nested association in as_json在 as_json 中排序嵌套关联
【发布时间】:2017-02-27 13:09:10
【问题描述】:
class User
  has_many :posts
end

我想用 as_json 方法渲染一个 json 哈希。

如何在不为关联设置默认顺序的情况下通过updated_at 属性对下面代码中的帖子进行排序?

user.as_json(include: {posts: {include: :comments})

这不会用作请求响应,我想避免在关联上设置默认排序。

【问题讨论】:

  • @Slava.K 感谢您的努力,但是在您找到的问题中,您在哪里看到 as_json
  • 该答案中列出的所有技术也适用于as_json。试试看吧。
  • @Slava.K 听起来棒极了!您能否举个例子,因为我尝试过但没有成功?
  • 您可以创建一个方法并使用 as_json 调用 user.as_json(methods: : permalink) 在此方法中以某种方式设置您的逻辑,这将为您提供带有 updated_at 顺序的记录。

标签: ruby-on-rails json ruby-on-rails-5


【解决方案1】:

您可以使用自定义方法代替范围:

class User < ApplicationRecord
  has_many :posts

  def updated_posts
    posts.order("posts.updated_at").as_json(include: :comments)
  end
end

user.as_json(methods: :updated_posts)

这将产生如下内容:

{
  # user attributes
  "updated_posts => [
    # posts with comments
  ]
}

如果您希望帖子严格在 posts 键下,您可以执行以下操作:

json = user.as_json(methods: :updated_posts)
json[:posts] = json.delete(:updated_posts)

【讨论】:

  • 非常感谢您提供有效的解决方案!但遗憾的是,似乎没有任何继承方式可以做到这一点。借助 :only:ecxept 等方便的辅助方法,这是雕刻小型 json 对象的一种非常好且快速的方法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-06-17
  • 1970-01-01
  • 2021-01-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多