任何人都可以提供有关要过滤的JSON响应中嵌套对象/关系的"最佳"方法的建议?
在下面的简单示例中,例如 Comment
具有软删除标志is_deleted = true
,我只想包括具有is_deleted = false
的注释。完成此操作的最佳方法是什么?
posts = Post.all
render json: posts.to_json(:include => [:comments])
我可以提出一个简单的解决方案。在Post
中,您可以从结果中范围删除注释,例如:
has_many :comments, -> { is_deleted: false }
这将仅返回那些未删除的注释。然后,您现有的JSON代码可以正常工作。
编辑1:
根据我们在评论中的讨论。
在Post
中创建便利方法。这将返回所有未删除的评论。
def visible_comments
comments.where(is_deleted: false)
end
然后,您可以按以下方式更改渲染方法:
render json: posts.to_json(:include => [:visible_comments])
这将调用Post
的visible_comments
方法,仅包括该方法返回的结果。
编辑模式
class Post < ActiveRecord::Base
def as_json(_options = {})
super only: [:id, :title],
include: {
comments: {
only: [:id, :comment_fieds]
}
end
end
class Comment < ActiveRecord::Base
default_scope { where is_deleted: false }
end
您只能在:[.....]中添加评论和发布字段。
posts = Post.all
render json: posts