RoR:未定义的方法`[]'为nil:NilClass

时间:2014-02-03 05:07:52

标签: ruby-on-rails ruby-on-rails-3

我正在使用以下代码而没有任何问题。函数querytags返回一组“产品”。 geturl函数检查产品是否有与之关联的图像。所有带图像的产品都会推送到productsProxy数组

@query = params[:tag]
@products = queryTags(@query)
@productsProxy = Array.new

if @products != nil
    @products.each do |p|
        tempProduct = ProductProxy.new(p)
        if tempProduct.getUrl(tempProduct.images[0]['id'], 'small', tempProduct.images[0]['file'])
        @productsProxy.push(tempProduct)
        end
    end
else
    @productProxy = []
end

然后我尝试在URL中添加另一个参数,并相应地更改了querytags函数。

@query = params[:tag]
@taxon = params[:taxon]
@products = queryTags(@query, @taxon)
@productsProxy = Array.new

if @products != nil
    @products.each do |p|
        tempProduct = ProductProxy.new(p)
        if tempProduct.getUrl(tempProduct.images[0]['id'], 'small', tempProduct.images[0]['file'])             #now showing error
        @productsProxy.push(tempProduct)
        end
    end
else
    @productProxy = []
end

但是我说明了nil:NilClass`的undefined method []':

if tempProduct.getUrl(tempProduct.images[0]['id'], 'small', tempProduct.images[0]['file'])

我在调试器的帮助下检查@products数组不为空。我无法弄清楚为什么我突然得到这个错误。请有人帮忙

1 个答案:

答案 0 :(得分:1)

这不是关于“@products”数组是否为空 - 如果它是空的,“@ product”迭代器将不会做任何事情。问题是您的某个产品要么缺少图像属性,要么图像[0]没有返回哈希值。出于调试目的,我首先添加“break if p.images.nil?”到你的迭代器的顶部并从那里开始。

相关问题