2012-12-28 21 views
0

我有一個客戶和發票模型。客戶有許多發票和發票屬於客戶。來自關聯的訪問屬性

class Customer < ActiveRecord::Base 
attr_accessible :billing_address, :customer_currency, :email, :first_name, :last_name, :mobile, :name, :payment_terms, :phase_type, :pays_vat 
validates_presence_of :first_name, :last_name, :mobile, :billing_address, :payment_terms, :phase_type, :customer_currency 

has_many :invoices 

validates :email, 
     :presence => true, 
     :uniqueness => true, 
     :email_format => true 

validates :name, :mobile, :presence => true, :uniqueness => true 
end 

發票型號是

class Invoice < ActiveRecord::Base 
belongs_to :customer 
attr_accessible :approved_by, :due_date, :invoice_date, :terms, :customer_id, :customer 

validates :invoice_date, presence: true 
validates :due_date, presence: true 
validates :customer, presence: true 

我試圖創建一個索引頁,其中列出了系統中所有的發票,這將發票顯示誰發票所屬的客戶名稱。我如何檢索並在我的模型和視圖中清楚地描述它?

回答

0

我認爲您已經創建了客戶和發票控制器和視圖(如果不通過generate scaffold)。在意見\發票\ index.html.erb然後列出發票:

<table> 
    <tr> 
    <th>Invoice</th> 
    <th>Customer/th> 
    </tr> 
<% @invoices.each do |invoice| %> 
    <tr> 
    <td><%= invoice.num %></td> 
    <td><%= invoice.customer.first_name %></td> 
    </tr> 
<% end %> 
</table> 

當然,你應該在控制器聲明@invoices/invoices_controller.rb

def index 
    @invoices = Invoice.includes(:customer).all 
end 
+1

你應該使用發票。包括(:customer)。所有這些都是爲了在迭代發票時避免額外的查詢。 –

+0

不,如果關聯是正確的,它將按照我所示的方式工作。 – alex

+0

肯定會的,但如果有10張發票,則必須進行11次sql查詢 - 獲取所有發票和每個發票的1(獲取客戶的first_name)。如果使用'includes'方法,則只有2個查詢。 –