2012-05-30 84 views
0

我有一個表單,用戶可以輸入發票付款。所以......Rails 3.呈現驗證錯誤

invoice has_many :payments 
payment belongs_to :invoice 

的問題是,當有驗證錯誤,比方說用戶不輸入所需的付款日期,我得到這個錯誤...

undefined method invoice_number for nil:NilClass 
Extracted source (around line #10): 
7: 
8: <div class="content-box-content"> 
9: <div class="tab-content default-tab" style="display: block; ">  
10: <h4>Invoice #<%= @invoice.invoice_number %> for <%= @invoice.company.name %></h4> 
11:  <p>Invoice Balance $<%= sprintf("%.2f", @invoice.balance) %></p> 
12: </div> 
13: </div> 

payments_controller.rb 
---------------------- 
def new 
    @invoice = Invoice.find(params[:invoice_id]) 
    @payment = @invoice.payments.build 

    respond_to do |format| 
    format.html 
    end 
end 

def create 
    @payment = Payment.new(params[:payment]) 
    respond_to do |format| 
    if @payment.save 
     format.html { redirect_to payments_path, notice: 'Payment was successfully created.' } 
    else 
     format.html { render action: "new" } 
    end 
    end 
end 

所以我知道我必須將@invoice添加到創建操作中,在render action: "new"的某處。我怎樣才能做到這一點?

回答

2

只需添加@invoice = @payment.invoice你做format.html { render action: "new" }之前,一切都應該工作

def create 
    @payment = Payment.new(params[:payment]) 
    respond_to do |format| 
    if @payment.save 
     format.html { redirect_to payments_path, notice: 'Payment was successfully created.' } 
    else 
     @invoice = @payment.invoice 
     format.html { render action: "new" } 
    end 
    end 
end 

調用渲染不是被管理只會渲染作用視圖的一個不同的動作。它不會調用正在呈現的操作的方法。

在換句話說:format.html { render action: "new" }只加載new.html.erb與在創建操作中指定的變量,def new是從來沒有碰過。因此,@invoice參數不存在,因爲您從未在創建操作中定義它。