Zubair Ahmed
Zubair Ahmed

Reputation: 17

View not showing data from associated table in Ruby On Rails

I'm very new to Rails and I've a problem with displaying data from associated table

here is what i have

class Candidate < ActiveRecord::Base
  has_many :emails  
end

class Email < ActiveRecord::Base
  belongs_to :candidate
end

class CandidatesController < ApplicationController 
  def index
  @candidates = Candidate.includes(:emails).all 
  end
end

in my view index.html.erb I have

<table>
 <% @candidates.each do |candidate| %> 
  <tr> 
    <td> Name: <%= candidate.name %> </td>
     <%  candidate.emails.each do |email_address| %> 
     <td> <%= email_address %> </td>
     <% end %>    
  </tr>
 <% end %>
</table>

Here is the output I'm getting in browser:

Name: Mohsin  #<Email:0xbd41114>
Name: Faysal  #<Email:0xbd40f0c>
Name: Adeel  #<Email:0xbd40d68>

Its only showing the data from candidates, not from the associated emails table, why? Can someone please help me??? I'm stuck here!

Upvotes: 0

Views: 900

Answers (3)

Gagan Gami
Gagan Gami

Reputation: 10251

#<Email:0xbd41114> this shows object of active record. You need to specify your field name from emails table in which column email-ids are stored.

for eg: you have stored all email-ids in emails table under email_id column then do it like:

<%  candidate.emails.each do |email_address| %> 
  <td> <%= email_address.email_id %> </td>
<% end %>

In short you need to specify field name like:

<%= email_address.column_name %>

Upvotes: 0

Saqib
Saqib

Reputation: 685

In your view code you are rendering email object, instead render a field of email object, something like

<table>
  <% @candidates.each do |candidate| %> 
    <tr> 
      <td> Name: <%= candidate.name %> </td>
      <%  candidate.emails.each do |email_address| %> 
        <td> <%= email_address.email %> </td>
      <% end %>    
    </tr>
  <% end %> 
</table>

Upvotes: 1

user3506853
user3506853

Reputation: 814

<%= email_address.email %>
or
<%= email_address.field_name %>

Upvotes: 2

Related Questions