Robin
Robin

Reputation: 8498

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?

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.

This complicates everything like API documentation and implementation in the clients, because we have to test for empty results, single results and array results.

How is it possible to always return a JSON array here?

Stack: Ruby 2.5.3; Rails 5.2.2

Upvotes: 1

Views: 868

Answers (1)

Ursus
Ursus

Reputation: 30056

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

Upvotes: 3

Related Questions