Rendering JSON for Multiple Rails Objects
This may be a terribly simple question, but this is what I noticed that worries me.
I'm trying to display JSON from one of my controller's methods, but it gives me an undefined `new 'for nil: NilClass method.
Here is the code causing the problem:
def index
@users = User.all
render json: @users
end
I noticed that when I try to display only one object for 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 the call was render json:
implicitly calling to_json
anyway, so why call, which twice solves my problem?
+3
source to share