1

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

0

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

2 Comments

Maybe he wants an array with just one element, if this is the case, he should use Entry.where(user: current_user).limit(1) that will generate the same query of Entry.find_by(user: current_user), but will return just one object in an ActiveRecord::Relation.
Thank you. I just forgot about that find_by only the first result.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.