0

我有一个表单,用户可以在其中输入发票付款。所以...

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". 我怎样才能做到这一点?

4

1 回答 1

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.erbdef new@invoice

于 2012-05-30T14:55:24.553 回答