I have a Customers model:
class Customer < ActiveRecord::Base
has_many :phone_numbers
end
and a Phone Numbers model
class PhoneNumber < ActiveRecord::Base
belongs_to :customer
end
In my view, I’m doing this:
<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>
and here is my controller for this action:
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
In the table in my view, I want to show the first phone number found for each customer listed in a phone number column – like:
Last Name first Name Phone
Smith John 3258889322
Jones Davey 3412555232
I’ve come up with multiple solutions to this problem, but none was very elegant. There must be a ‘Rails Way’ to do this that is really snazzy, as this seems like a common situation for a web application developer to be faced with.
In your view:
Your association will take care of creating those phone-number-related attribute accessors for you. You can see all of the methods that are created for you with a
has_manyassociation here.