Fameless
Fameless

Reputation: 345

Issue to show data from relational database tables in rails

I am a newbie in ruby on rails it's also my first ruby application.

I want to show data from two tables these are

applied_jobs table: it contains the below columns:

applied_jobs_id | jobseeker_id | expected_salary

jobseekers table: it contains the below columns:

jobseeker_id | year_of_experience | name

My view file codes:

 <tbody>
    <% @applicants_view.each do | applicants | %>
      <tr>
        <td><%=  applicants.jobseeker.name%></td>
        <td><%=applicants.jobseeker.year_of_experience %></td>
        <td><%= applicants.expected_salary %></td>
       </tr>
     <% end %>
  </tbody>

My controller codes:

def applicantsList

   @applicants_view = AppliedJob.paginate(page: params[:page],

:per_page => 4).order('applied_jobs_id DESC')

end

My applied_job model codes:

class AppliedJob < ActiveRecord::Base

    belongs_to :jobseeker
end

My jobseeker model codes:

class Jobseeker < ActiveRecord::Base

    has_one :applied_job

end

When I try to show data it's showing the below error

 C:/wamp/www/hire_us/app/views/applicants_list/applicantsList.html.erb
   where line #51 raised:

  undefined method `name' for nil:NilClass

  Rails.root: C:/wamp/www/hire_us
  Application Trace | Framework Trace | Full Trace

  app/views/applicants_list/applicantsList.html.erb:51:in `block in
 _app_views_applicants_list_applicants_ist_html_erb___1439381291_141337560'

  app/views/applicants_list/applicantsList.html.erb:49:in
    '_app_views_applicants_list_applicants_ist_html_erb___1439381291_141337560'

Someone can help me, please to identify where the bug?

Upvotes: 1

Views: 89

Answers (1)

Ho Man
Ho Man

Reputation: 2345

You can avoid the error by adding

<% @applicants_view.each do | applicants | %>
   <% next unless applicants.jobseeker %>
   ...
<% end %>

or

<% @applicants_view.each do | applicants | %>
   <% applicants.jobseeker.try(:name) %>
   ...
<% end %>

Upvotes: 2

Related Questions