How do I list associated attributes in my Rails 3 view? -
i have customers model:
class customer < activerecord::base has_many :phone_numbers end
and phone numbers model
class phonenumber < activerecord::base belongs_to :customer end
in 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 |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 controller action:
def index @customers = customer.find(:all, :limit => 10, :order => 'last_name') flash.now[:notice] = 'enter customer last or first name. fields case-sensitive.' end
in table in view, want show first phone number found each customer listed in phone number column - like:
last name first name phone smith john 3258889322 jones davey 3412555232
i've come multiple solutions problem, none elegant. there must 'rails way' snazzy, seems common situation web application developer faced with.
in view:
<table id="customersearch"> <tr> <th>last name</th> <th>first name</th> <th>phone</th> <th></th> <th></th> </tr> <% @customers.each |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>
your association take care of creating phone-number-related attribute accessors you. can see of methods created has_many
association here.
Comments
Post a Comment