0

这是在我的控制器中

def results
#searches with tags
@pictures = Picture.all
@alltags = Tag.all
searchkey = params['my_input']
pList = []
listsize = 0
while listsize < @pictures.size
  pList[listsize] = 0
  listsize += 1
end
@alltags.each do |tag|
  if searchkey == tag.tagcontent
    pList[tag.picture.id-1] += 1
  end
end
@pictures.each do |picture|
  if searchkey == picture.name
    pList[picture.id-1] += 1
  end
end
@pictures = @pictures.sort {|pic1, pic2| pList[pic2.id-1] <=> pList[pic1.id - 1]}

结尾

调用此错误时出现此错误

SearchController 中的 NoMethodError#results

当你没想到时,你有一个 nil 对象!您可能期望有一个 Array 的实例。评估 nil.+ Rails.root 时发生错误:/Users/kevinmohamed/SnapSort/server

应用程序跟踪 | 框架跟踪 | 完整跟踪 app/controllers/search_controller.rb:31:in block in results' app/controllers/search_controller.rb:29:ineach' app/controllers/search_controller.rb:29:in `results'

31 是 pList[picture.id-1] += 1 ,29 是 @pictures.each 做 |picture|,为什么会发生这个错误

4

2 回答 2

1

pList 是一个数组,索引为 0, 1, 2, 3, 4...

你的线

pList[picture.id-1] += 1

很可能是指一个不存在的索引。例如,如果 pList 有 50 个成员,则它的指数为 0-49。如果上图的 id 是 7891,那么它会尝试寻找一个 7890 的索引,这个索引当然是不存在的。这将返回 nil,并尝试执行“nil += 1”,这是您的错误的来源。

也许 pList 应该是由图片 ID 键入的哈希?取决于您要完成的工作。但无论你想做什么,几乎可以肯定,在 Ruby 中可以用一种不那么冗长的方式来表达它。

于 2011-10-14T20:14:00.073 回答
0

当您正在迭代的某些东西在它不期望的情况下产生了一个 nil 时,就会发生此错误。您的控制器中有很多代码。我建议将其中一些逻辑转移到模型的方法中并为其编写一些测试,包括在标签或图片不可用时引发错误。然后您可以在控制器中挽救错误以显示更友好的错误消息。

于 2011-10-14T20:13:55.643 回答