[英]Undefined method `keys' for nil:NilClass error on rails
I tried to run web server and it shows the following error: 我试图运行Web服务器,它显示以下错误:
undefined method `keys' for nil:NilClass error on rails 导轨上出现nil:NilClass错误的未定义方法“键”
Extracted source (around line #21): 提取的源(围绕第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. 当我尝试将render :json => shopsList
为render :json => commentList
,注释列表在服务器中将显示为json格式。
Also, is there something wrong with the way I access or declare the commentList array? 另外,我访问或声明commentList数组的方式是否有问题? 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
您需要传递一个哈希值以进行render
try this 尝试这个
shopsList = [sh1, sh2, sh3, sh4]
render :json => {:success=>true, :data=>shopsList}
Can you please post the stacktrace? 你能发布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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.