简体   繁体   English

如何在Ruby On Rails中为单个结果返回一个JSON数组?

[英]How to always return a JSON array for single result in Ruby On Rails?

What is the easiest or anticipated way to always return a JSON array from a API controller in Ruby On Rails? 在Ruby On Rails中始终从API控制器返回JSON数组的最简单或预期的方法是什么?

Let's say I've the following controller action: 假设我有以下控制器操作:

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

A list of entries is returned. 返回条目列表。 Sometimes the result is only one entry, so to_json() doesn't create a JSON array but a JSON object instead. 有时结果只有一个条目,因此to_json()不会创建JSON数组而是创建JSON对象。

This complicates everything like API documentation and implementation in the clients, because we have to test for empty results, single results and array results. 这使API文档和客户端实现等所有内容变得复杂,因为我们必须测试空结果,单个结果和数组结果。

How is it possible to always return a JSON array here? 怎么可能总是在这里返回一个JSON数组?

Stack: Ruby 2.5.3; Stack:Ruby 2.5.3; Rails 5.2.2 Rails 5.2.2

Try changing this 尝试改变这个

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

to

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

find_by returns an object, whereas where an ActiveRecord::Relation find_by返回一个对象,而where一个ActiveRecord::Relation

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM