在RubyonRails中,如何总是为单个结果返回JSON数组



在Ruby On Rails中,总是从API控制器返回JSON数组的最简单或预期的方法是什么?

假设我有以下控制器动作:

def index
render json: Entry.all.includes(:user).to_json(include: :user) if current_user.has_role?(:administrator)
render json: Entry.find_by(user: current_user).to_json(include: :user)
end

将返回一个条目列表。有时结果只有一个条目,因此to_json()不会创建JSON数组,而是创建JSON对象。

这使得客户端中的API文档和实现等一切都变得复杂,因为我们必须测试空结果、单个结果和数组结果。

怎么可能总是在这里返回JSON数组?

堆栈:Ruby 2.5.3;轨道5.2.2

尝试更改此

render json: Entry.find_by(user: current_user).to_json(include: :user)

render json: Entry.where(user: current_user).to_json(include: :user)

find_by返回一个对象,而where返回ActiveRecord::Relation

最新更新