3

This might be a terribly simple question, but this is just something I noticed that is bothering me.

I'm trying to render JSON from one of my controller's methods, but it's giving me a "undefined method `new' for nil:NilClass" error.

Here's the code that's causing the problem:

def index
    @users = User.all
    render json: @users
end

I noticed that when I try to render only one object to JSON, everything works fine:

def show
    @user = User.find(params[:id])
    render json: @user
end

Or when I call to_json on the @users object:

def index
    @users = User.all
    render json: @users.to_json
end

I was under the impression that calling render json: was implicitly calling to_json anyway, so why would calling that twice solve my issue?

3
  • I suppose this is because the response has to be the only one json object, not many :) Commented Jun 13, 2015 at 8:34
  • Your code looks reasonable. Can you post the rest of the undefined method new stack trace? Commented Jun 13, 2015 at 16:23
  • @rubchick that's what I was thinking, but I was just a little confused as to why render json: wouldn't automatically take the array. Commented Jun 13, 2015 at 19:31

1 Answer 1

1

I believe that it's an issue with @users being an array of objects that needs each object to be converted first before the whole array is reassembled and output as JSON.

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

Comments

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.