2013-05-03 211 views
0

我有嵌套資源訪問父屬性

resources :invoices do 
    resources :payments 
end 

發票模型如下:

class Invoice < ActiveRecord::Base 

belongs_to :customer, :inverse_of => :invoices 
attr_accessible :due_date, :invoice_date, :reading_ids, :customer_id, :customer, :status, :amount, :balance 

has_many :invoice_items, :dependent => :destroy 
has_many :payments, :dependent => :destroy 
end 

的付款模式如下:

class Payment < ActiveRecord::Base 
attr_accessible :amount, :method, :payment_date, :reference_no, :invoice_id 
belongs_to :invoice 
end 

支付控制器如下:

class PaymentsController < ApplicationController 
before_filter :authenticate_user! 

def new 
    invoice = Invoice.find(params[:invoice_id]) 
    @payment = invoice.payments.build 
respond_to do |format| 
    format.html #new.html.erb 
end 
    end 
    end 

我創建了一個視圖來記錄新的付款,並希望在此視圖中顯示客戶詳細信息(名稱),我該如何解決?

Payments顯示

<%= simple_form_for [@payment.invoice, @payment], :html => { :class => 'form-horizontal' } do |f| %> 
<%= render "shared/error_messages", :target => @payment %> 

<h5> Invoice Details </h5> 
<%= f.input :invoice_id, disabled: true, as: :string %> 
<%= f.input :method, as: :select, :collection => [['Cash','Cash'],['Cheque','Cheque'],['In-House transfer','In-House transfer'],['Account Ledger','Account ledger']], :selected => ['Cash','Cash'] %> 
    <%= f.input :reference_no, as: :string %> 
    <%= f.input :payment_date, as: :string, input_html: { class: "datepicker" } %> 
<% end %> 

回答

0

只需使用:

<%= @payment.invoice.customer.name %> 

任何地方的視圖。

+0

謝謝,它工作正常。還有一個問題,如何通過發票模型訪問餘額並在付款視圖中將其顯示爲「已收金額」元素下的默認值,我可以使用@ payment.invoice.balance – zurik 2013-05-03 09:29:53

+0

不客氣。確切地說,使用'@ payment.invoice.balance'應該可以。您可以將您的問題標記爲已回答。 – 2013-05-03 09:33:59