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

时间:2013-12-16 09:41:29

标签: ruby-on-rails ruby json

我尝试运行Web服务器并显示以下错误:

  

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

提取的来源(第21行):

     shopsList = [st1, st2, st3, st4]

     render :json => shopsList
   end
end

以下是文件:

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

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

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

2 个答案:

答案 0 :(得分:0)

您需要将哈希值传递给render

试试这个

shopsList = [sh1, sh2, sh3, sh4]

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

答案 1 :(得分:0)

请你发布堆栈跟踪吗?

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

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