I tried to run web server and it shows the following error:
undefined method `keys' for nil:NilClass error on rails
Extracted source (around line #21):
shopsList = [st1, st2, st3, st4]
render :json => shopsList
end
end
Here are the files:
class Shop < ActiveRecord::Base
attr_accessor :name, :description, :comments
def initialize(name, description, comments)
@name = name
@description = description
@comments = []
end
end
class Comment
attr_accessor :id, :name, :content
def initialize(id, name, content)
@id = id
@name = name
@content = content
end
end
class ShopsController < ApplicationController
def index
end
def shops
com1 = Comment.new("FX991", "Goat", "Delicious!")
com2 = Comment.new("F2888", "Cow", "Amazing!")
com3 = Comment.new("GH555", "Cat", "Yummm!")
com4 = Comment.new("HY666", "Fish", "Mouth watering!")
commentList = [com1, com2, com3, com4]
sh1 = Shop.new("AAAA", "Je", commentList[0])
sh2 = Shop.new("NNNN", "Te", commentList[1])
sh3 = Shop.new("CCCC", "Be", commentList[1])
sh4 = Shop.new("DDDD", "He", commentList[1])
shopsList = [sh1, sh2, sh3, sh4]
render :json => shopsList
end
end
When I tried changing render :json => shopsList
to render :json => commentList
, the comment list would show as json format in the server.
Also, is there something wrong with the way I access or declare the commentList array? The contents of the array won't show when I try to access it. It just displays "[]"
You need to pass a hash to render
try this
shopsList = [sh1, sh2, sh3, sh4]
render :json => {:success=>true, :data=>shopsList}
Can you please post the stacktrace?
I don`t think "render" is causing the error, I think it happens earlier on in the callstack.
#tested this, it is valid code
def mytest
data = ["1","2","3"]
render :json => data
end
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.