开发者

Rails 3.1 associations?

I have a Rails 3.1.1 application with the following models:

Company
Member

The two models have the following associations:

Company - has_many :members
Member  - belongs_to :company

When adding members I can enter the company ID number and the record is linked su开发者_如何学运维ccessfully, I can lookup members through the company etc.

When I am working on the member show view I would like to 'pull' in details of the company.

Currently I have the following in the show view:

<h1>Listing members</h1>

<table>
  <tr>
    <th>Name</th>
    <th>Mobile</th>
    <th>Email</th>
    <th>Qualifications</th>
    <th>Membership</th>
    <th>Company</th>
    <th></th>
    <th></th>
    <th></th>
  </tr>

<% @members.each do |member| %>
  <tr>
    <td><%= member.name %></td>
    <td><%= member.mobile %></td>
    <td><%= member.email %></td>
    <td><%= member.qualifications %></td>
    <td><%= member.membership %></td>
    <td><%= @member.company.company_id %></td>
    <td><%= link_to 'Show', member %></td>
    <td><%= link_to 'Edit', edit_member_path(member) %></td>
    <td><%= link_to 'Destroy', member, confirm: 'Are you sure?', method: :delete %></td>
  </tr>
<% end %>
</table>

How do I go about pulling in a field from the related company? For example the company model has two fields (latitude and longitude).


Your loop should look like this:

<% @members.each do |member| %>
  <tr>
    <td><%= member.name %></td>
    <td><%= member.mobile %></td>
    <td><%= member.email %></td>
    <td><%= member.qualifications %></td>
    <td><%= member.membership %></td>
    <td><%= member.company_id %></td>
    <td><%= member.company.latitude %></td>
    <td><%= link_to member.company.name, member.company %></td>
    <td><%= link_to 'Show', member %></td>
    <td><%= link_to 'Edit', edit_member_path(member) %></td>
    <td><%= link_to 'Destroy', member, confirm: 'Are you sure?', method: :delete %></td>
  </tr>
<% end %>

company_id is defined on the Member model, you cannot access it through member.company.company_id. To access a field on the related company model, use member.company.my_field.

These will only work in the members loop, as they access the |member| variable which is passed to the block.


@member.company.latitude

et cetera. Please let me know if you want clarification or more information.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜