2012-01-17 33 views
1

我有下面的代码在我的模型:Rails的模型方法失败

attr_accessor :display_time_reader 
attr_reader :display_time_reader 

具有以下display_time_reader =方法:

def display_time_reader=(days_before_start) 
    self.date_to_show_ad=self.start_time-days_before_start.to_i.days 
end 

我提交给它具有以下PARAMS:

Parameters: {"utf8"=>"✓", "authenticity_token"=>"wb7acGREdNH2aeuYjye51wwaWdMXgTYvAcNxoDR9HAE=", "sale"=>{"start_time(3i)"=>"13", "start_time(2i)"=>"1", "start_time(1i)"=>"2012", "start_time(4i)"=>"23", "start_time(5i)"=>"00", "end_time(3i)"=>"14", "end_time(2i)"=>"1", "end_time(1i)"=>"2012", "end_time(4i)"=>"01", "end_time(5i)"=>"00", "display_time_reader"=>"7"}, "commit"=>"create"} 

不过,我发现了以下错误时返回:

当你没有想到它时,你有一个零对象!您可能需要 Array的实例。而评估 nil.-发生错误

控制器代码:

def new 
    user = User.find(current_user.id) 
    @sale = user.sales.build 
    @locations = user.locations 
    1.times { @sale.items.build; @sale.build_location } 
end 

def create 
@sale = Sale.new(params[:sale]) 
@sale.user_id = current_user.id 

logger.debug "Sale object!!! #{@sale.inspect}" 
respond_to do |format| 
    if @sale.save 
    format.html { redirect_to @sale, notice: 'Sale was successfully created.' } 
    format.json { render json: @sale, status: :created, location: @sale } 
    else 
    format.html { render action: "new" } 
    format.json { render json: @sale.errors, status: :unprocessable_entity } 
    end 
    end 
end 

任何想法可能会导致什么呢?

+0

您提交给一个操作,而不是一个模型。什么是零? – 2012-01-17 22:37:49

+0

@DaveNewton - 上面介绍的代码在模型中。它没有指定什么是零。 – Elliot 2012-01-17 22:38:59

+0

我知道它是在一个模型中,但我们并不真正知道什么时候发生零,在什么情况下等等。 – 2012-01-17 22:40:25

回答

0

看起来像self.start_time可能是nil(因此调用方法-是未定义的)。你能保证self.start_time不是nil

+0

但参数表明,应该不是无? – Elliot 2012-01-17 22:40:46

+0

不,'self.start_time'是唯一的东西(在你迄今为止显示的任何东西中),它有调用它的减法方法。如果'self.start_time'为零,那么它不会有'-'方法。确保'self.start_time'被初始化,无论是在构造上还是在该方法中。 – 2012-01-17 23:23:34

0

看起来初始化器的哈希条目没有在值试图被减去之前设置,因此发生了一个零错误。通过使用before_save回调修复了这个问题,因为这可以保证每次保存记录时都会计算出正确的start_time。