首页 > 解决方案 > 如何在AMS上的括号内渲染json一些没有括号的变量

问题描述

我想知道是否可以在没有参数的情况下使用带有 AMS 的括号渲染变量?

举个例子:

render json: { comments: @comments, status: 200, hasMore: hasMore }

我想只渲染没有评论的@comments:并在json上显示hasMore:hasMore,这可能在括号内!

用这种方式

render json: @comments, hasMore: hasMore,  include: ['user', 'replies.**']

没有在 json 上显示 hasMore

标签: ruby-on-railsrubyruby-on-rails-5active-model-serializers

解决方案


如果要渲染 json,则需要确保作为 json 传递的内容实际上是有效的 json。这是一个最简单的例子:

# this does not work and will throw a syntax error
render json: 'foo: 'foo', bar: 'bar'

# this works
render json: {foo: 'foo', bar: 'bar'}


# this works because it will render an array type
render json: @comments # assuming that is a collection

推荐阅读