[英]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.