ruby on rails 3 -关联访问属性



我有一个客户和发票模型。一个客户有许多发票和一个belongs_to一个客户的发票。

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

我正在尝试创建一个索引页,列出系统中的所有发票,这将发票显示发票所属的客户名称。我如何检索它并在我的模型和视图中清楚地描述它?

我认为您已经创建了客户和发票控制器和视图(如果不是通过generate scaffold)。然后在viewsinvoicesindex.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>
当然,你应该在controllers/invoices_controller.rb 中声明@invoices
def index
  @invoices = Invoice.includes(:customer).all
end

相关内容

  • 没有找到相关文章

最新更新