如何在Rails 3视图中列出关联的属性?

时间:2011-01-25 21:14:13

标签: ruby-on-rails-3

我有一个客户模型:

class Customer < ActiveRecord::Base
  has_many    :phone_numbers
end

和电话号码模型

class PhoneNumber < ActiveRecord::Base
  belongs_to :customer
end

在我看来,我这样做:

<table id="customerSearch">
  <tr>
    <th>Last name</th>
    <th>First name</th>
    <th></th>
    <th></th>
    <th></th>
  </tr>
<% @customers.each do |customer| %>
  <tr>
    <td><%= customer.last_name %></td>
    <td><%= customer.first_name %></td>
    <td><%= link_to 'Show', customer %></td>
    <td><%= link_to 'Edit', edit_customer_path(customer) %></td>
  </tr>
<% end %>
</table>

这是我的控制器:

def index
  @customers = Customer.find(:all, :limit => 10, :order => 'last_name')
  flash.now[:notice] = 'Enter customer last or first name. Fields are case-sensitive.'
end

在我看来的表格中,我想显示为电话号码栏中列出的每位客户找到的第一个电话号码 - 例如:

Last Name    first Name    Phone

Smith        John          3258889322
Jones        Davey         3412555232

我已经为这个问题提出了多种解决方案,但没有一个非常优雅。必须有一个'Rails Way'来做这个非常时髦的事情,因为这似乎是Web应用程序开发人员面临的常见情况。

1 个答案:

答案 0 :(得分:0)

在您看来:

<table id="customerSearch">
  <tr>
    <th>Last name</th>
    <th>First name</th>
    <th>Phone</th>
    <th></th>
    <th></th>
  </tr>
<% @customers.each do |customer| %>
  <tr>
    <td><%= customer.last_name %></td>
    <td><%= customer.first_name %></td>
    <td><%= customer.phone_numbers.first.number if customer.phones.exists? %>
    <td><%= link_to 'Show', customer %></td>
    <td><%= link_to 'Edit', edit_customer_path(customer) %></td>
  </tr>
<% end %>
</table>

您的关联将负责为您创建与电话号码相关的属性访问者。您可以使用has_many关联here查看为您创建的所有方法。

相关问题