RoR:基本的外键问题

时间:2009-11-21 19:27:41

标签: ruby-on-rails

我目前有一个简单的查找表。当我显示agency时,我想显示locality.name而不是locality_idLocality.name存储在locality表中。只有id存储在agency表中。

下面显示locality_id,我希望它显示locality_name

我该怎么做?

代理商控制器

def index
  @agencies = Agency.all
  respond_to do |format|
    format.html # index.html.erb
    format.xml  { render :xml => @agencies }
  end
end

代理商指数

<% @agencies.each do |agency| %>
  <p>
    <b>Agency:</b>
    <%=h @agency.agency %>
  </p>
  <p>
    <b>Locality:</b>
    <%=h @agency.locality_id %>
  </p>
<% end %>

同样,我知道这是一个基本问题所以我很感激帮助

1 个答案:

答案 0 :(得分:2)

只需在视图中进行更改即可。

<% @agencies.each do |agency| %>

<p>
<b>Agency:</b>
<%=h @agency.agency %>
</p>

<p>
<b>Locality:</b>
<%=h @agency.locality.name %> <!-- this will bomb out if there agencies that 
                                   don't have a locality - if that's an issue, 
                                   add "if @agency.locality" to the end. -->
</p>
<% end %>