Rails 控制器中出现 NoMethodError
这是在我的控制器
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]}
端,
调用 NoMethodError 时,就会出现此错误
当在 SearchController#results 中
。当您没有预料到时,您有一个 nil 对象! 您可能期望一个 Array 的实例。 评估 nil 时发生错误。+ Rails.root:/Users/kevinmohamed/SnapSort/server
应用程序跟踪 |框架跟踪 |完整追踪 app/controllers/search_controller.rb:31:in 结果块' app/controllers/search_controller.rb:29:in
每个' app/controllers/search_controller.rb:29:in `results'
31 是 pList[picture.id-1] += 1 , 29 是 @pictures.each do |picture| ,为什么会发生这个错误
this is in my controller
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]}
end
this error comes when this is called
NoMethodError in SearchController#results
You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.+
Rails.root: /Users/kevinmohamed/SnapSort/server
Application Trace | Framework Trace | Full Trace
app/controllers/search_controller.rb:31:in block in results'
each'
app/controllers/search_controller.rb:29:in
app/controllers/search_controller.rb:29:in `results'
31 is pList[picture.id-1] += 1 , 29 is @pictures.each do |picture|, why is this error happening
pList 是一个数组,索引为 0、1、2、3、4...
您的行
可能引用了不存在的索引。例如,如果 pList 有 50 个成员,则其索引为 0-49。如果上图的id是7891,那么它会尝试寻找7890的索引,当然这个索引不存在。这将返回 nil,并尝试执行“nil += 1”,这就是错误的来源。
也许 pList 应该是一个由图片 id 键控的哈希?取决于您想要实现的目标。但无论您想要做什么,几乎可以肯定有一种更简洁的方式可以用 Ruby 来表达它。
pList is an array, indexed with 0, 1, 2, 3, 4...
Your line
is likely to refer to an index which doesn't exist. For example, if pList has 50 members, it has indecies 0-49. If the id of the above picture is 7891, then it will try to find an index of 7890 which of course doesn't exist. This will return nil, and try to execute "nil += 1", which is where your error is coming from.
Perhaps pList should be a Hash keyed by picture ids? Depends on what you're trying to accomplish. But whatever you're trying to do, there is almost certainly a less verbose way of expressing it in Ruby.