nil的未定义方法`keys':rails上的NilClass错误

时间:2022-07-21 20:40:14

I tried to run web server and it shows the following error:

我试图运行Web服务器,它显示以下错误:

undefined method `keys' for nil:NilClass error on rails

nil的undefined方法`keys':rails上的NilClass错误

Extracted source (around line #21):

提取的来源(第21行):

     shopsList = [st1, st2, st3, st4]

     render :json => shopsList
   end
end

Here are the files:

这是文件:

shop.rb

class Shop < ActiveRecord::Base
  attr_accessor :name, :description, :comments

  def initialize(name, description, comments)
    @name = name
    @description = description
    @comments = []
  end
end

comment.rb

class Comment
  attr_accessor :id, :name, :content

  def initialize(id, name, content)
    @id = id
    @name = name
    @content = content
  end
end

shops_controller.rb

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.

当我尝试更改渲染:json => shopsList渲染:json => commentList时,注释列表将在服务器中显示为json格式。

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 "[]"

另外,我访问或声明commentList数组的方式有问题吗?当我尝试访问它时,数组的内容将不会显示。它只显示“[]”

2 个解决方案

#1


0  

You need to pass a hash to render

您需要传递一个哈希来渲染

try this

尝试这个

shopsList = [sh1, sh2, sh3, sh4]

render :json => {:success=>true, :data=>shopsList}

#2


0  

Can you please post the stacktrace?

你可以发布堆栈跟踪吗?

I don`t think "render" is causing the error, I think it happens earlier on in the callstack.

我不认为“渲染”导致错误,我认为它发生在callstack的早期。

#tested this, it is valid code
def mytest
  data = ["1","2","3"]
  render :json => data
end

#1


0  

You need to pass a hash to render

您需要传递一个哈希来渲染

try this

尝试这个

shopsList = [sh1, sh2, sh3, sh4]

render :json => {:success=>true, :data=>shopsList}

#2


0  

Can you please post the stacktrace?

你可以发布堆栈跟踪吗?

I don`t think "render" is causing the error, I think it happens earlier on in the callstack.

我不认为“渲染”导致错误,我认为它发生在callstack的早期。

#tested this, it is valid code
def mytest
  data = ["1","2","3"]
  render :json => data
end