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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With