sulimmesh
sulimmesh

Reputation: 763

Rendering JSON for multiple Rails objects

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?

Upvotes: 3

Views: 559

Answers (1)

letsgoduke
letsgoduke

Reputation: 40

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.

Upvotes: 1

Related Questions