[英]Undefined method `keys' for nil:NilClass error on rails
我试图运行Web服务器,它显示以下错误:
导轨上出现nil:NilClass错误的未定义方法“键”
提取的源(围绕第21行):
shopsList = [st1, st2, st3, st4]
render :json => shopsList
end
end
这些是文件:
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
当我尝试将render :json => shopsList
为render :json => commentList
,注释列表在服务器中将显示为json格式。
另外,我访问或声明commentList数组的方式是否有问题? 当我尝试访问该数组时,不会显示该数组的内容。 它只显示“ []”
您需要传递一个哈希值以进行render
尝试这个
shopsList = [sh1, sh2, sh3, sh4]
render :json => {:success=>true, :data=>shopsList}
你能发布stacktrace吗?
我不认为“渲染”会导致错误,我认为它发生在调用堆栈的前面。
#tested this, it is valid code
def mytest
data = ["1","2","3"]
render :json => data
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.