简体   繁体   中英

Rails undefined method `+' for nil:NilClass

I have a method 'calc_price' that was working previously, and still works in console, but is now giving me the following error in a browser:

NoMethodError in Quotes#index

undefined method `+' for nil:NilClass

18:             Price: $<%= f.calc_price %><br />

app/models/quote.rb:33:in `block in calc_price'
app/models/quote.rb:13:in `calc_price'
app/views/quotes/index.html.erb:18:in `block in _app_views_quotes_index_html_erb__1788058106025144185_70227449765940'
app/views/quotes/index.html.erb:15:in `each' 
app/views/quotes/index.html.erb:15:in `_app_views_quotes_index_html_erb__1788058106025144185_70227449765940'

The fact that it still works in console is confusing to me, especially since I didn't change the method at all for it to break. The method:

def calc_price
    self.items.each do |item|
        pr = if item.amount < 10
            item.product.pricerange0
        elsif item.amount < 25 
            item.product.pricerange1
        elsif item.amount < 50 
            item.product.pricerange2
        elsif item.amount < 100
            item.product.pricerange3
        elsif item.amount < 250
            item.product.pricerange4
        elsif item.amount < 500
            item.product.pricerange5
        end
        screens = 0
        sd = item.shirtdesigns.count
        pd = item.pantdesigns.count
        screens = (sd+pd)
        screenprice = (screens*25)
        inkprice = ((item.inkcolors-1)*0.5)
        newprice = ((pr+inkprice)*item.amount+screenprice)
        item.price = newprice
        item.save
    end
    newprice = self.items.sum('price')
    self.price = newprice
    self.save
    return self.price
end

quote controller

def index
  @quote = Quote.find(:all)
  @myquotes = Quote.find(:all, :conditions => { :user_email => current_user.email })
end

I tried adding screenprice = 0, newprice = 0 and inkprice = 0 to see if that would make a difference but it did not.

If it still works in console does that mean maybe its not the method itself that is broken?

Any help would be greatly appreciated! Thanks

pr is most likely nil. An item with an amount greater than 500 would result in pr being nil in the code above.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM