【问题标题】:Create a nested JSON with filtered ActiveRecord objects使用过滤的 ActiveRecord 对象创建嵌套 JSON
【发布时间】:2014-09-05 14:45:00
【问题描述】:
我需要创建一个包含 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) 而不是所有照片
谁能告诉我如何实现这一目标?
非常感谢
【问题讨论】:
标签:
ruby-on-rails
ruby
json
activerecord
【解决方案1】:
执行此操作的一种方法是创建一个经过过滤以仅显示“共享照片”的关联,然后将其包含在您的 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)