【发布时间】:2013-11-04 19:51:24
【问题描述】:
我有一个方法 'calc_price' 以前可以使用,现在仍然可以在控制台中使用,但现在在浏览器中出现以下错误:
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'
它仍然在控制台中工作的事实让我感到困惑,特别是因为我根本没有改变方法让它崩溃。方法:
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
报价控制器
def index
@quote = Quote.find(:all)
@myquotes = Quote.find(:all, :conditions => { :user_email => current_user.email })
end
我尝试添加 screenprice = 0、newprice = 0 和 inkprice = 0 以查看是否会有所作为,但没有。
如果它仍然在控制台中工作,这是否意味着它可能不是被破坏的方法本身?
任何帮助将不胜感激!谢谢
【问题讨论】:
-
好像
pr是零。 -
@SergioTulentsev pr 由顶部的 if 语句定义,item.product.pricerange0-5 为小数。
-
如果我见过这种方法,那是一种糟糕的方法。您可能应该首先重新考虑如何对定价进行建模,为代码编写测试,将庞大的 6 分支条件语句及其后的过程重构为更简洁的方法,并在不需要的地方删除显式调用者(例如几乎所有的
self.'s)。 -
@coreyward 你能详细说明不需要哪个 self.'s 吗?
-
Self 是一个隐式接收者——你不需要指定它,除非解释器的意图不明确。当你不做作业时,几乎不需要
self。在您的代码中,self.可以从self.items.*、self.save、self.price中删除(但不是self.price=)。
标签: ruby-on-rails methods