gpt4 book ai didi

ruby-on-rails - 使用过滤的 ActiveRecord 对象创建嵌套的 JSON

转载 作者:太空宇宙 更新时间:2023-11-03 18:16:51 25 4
gpt4 key购买 nike

我需要创建一个包含 3 个级别的事件记录对象的嵌套 JSON 数据,如下所示:

  • 联系人有很多歌手
  • Chantiers 有很多照片
  render :json => contact.as_json(include: { 
chantier: { include: {
photo: { only: [:url, :titre, :commentaires, :sharing]} },
only: [:id, :nom_chantier]}
}, only: [:id, :type, :email, :firstname, :lastname])

目前,JSON 是与联系人关联的所有记录。但是,我需要限制 3 级对象 Photo 以仅显示那些“共享”字段等于 true 的记录。

类似于:Photo.where(sharing: true) 而不是所有照片

任何人都可以就如何实现这一目标提出建议吗?

非常感谢

最佳答案

您可以执行此操作的一种方法是创建一个经过过滤以仅显示“共享照片”的关联,然后将其包含在您的 JSON 输出中。在您的 Contact 模型中,添加以下内容:

# You probably have something like this already:
has_many :photos

# Below is what you need to add

# Rails 4
has_many :shared_photos, -> { where(shared: true) }, source: :photos

# Rails 3
has_many :shared_photos, conditions: lambda { where(shared: true) }, source: :photos

设置条件关联后,您可以像通常包含关联一样在 as_json 调用中使用它,如下所示:

render :json => contact.as_json(include: :shared_photos)

关于ruby-on-rails - 使用过滤的 ActiveRecord 对象创建嵌套的 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24757626/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com