开发者

RoR: Basic foreign key question

开发者 https://www.devze.com 2022-12-12 07:22 出处:网络
I currently have a a simple lookup table. When I display an agency I would like to display the locality.name rather than the locality_id. The Locality.name is stored in the locality table. Just the id

I currently have a a simple lookup table. When I display an agency I would like to display the locality.name rather than the locality_id. The Locality.name is stored in the locality table. Just the id is stored in the agency table.

Below shows the locality_id, I would like for it to show the locality_name instead.

How do I do this?

agency controller

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

agency index

<% @agencies.each do |agency| %>
  <p>
    <b>Agency:</b>
    <%=h @agency.agency %>
  </p>
  <p>
    <开发者_开发百科;b>Locality:</b>
    <%=h @agency.locality_id %>
  </p>
<% end %>

Again, I know this is a basic question so I appreciate the help


Just change it in your view.

<% @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 %>
0

精彩评论

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

关注公众号