SkyKOG
SkyKOG

Reputation: 287

Rails undefined method `hospital' for nil:NilClass

Respected ppl ...

In my application i want to display the last hospital name for a given employee ...

for which i tried this :

<%= @employee.postings.last.hospital.hospital_name %>

All the required associations are correct ...as this works perfectly for all the employees who have a posting ... but i get the error for the employees who dont have even a single posting ...

I tried doing

<%= @employee.postings.last.hospital.hospital_name.to_s %>

and even

<% if [email protected]? %>

and even a "try" function ....

I just want it to not display any data when there dosent exist one ... instead of the intimidating error ...

if i could just learn how to skip over printing nil values then it would be awesome ..as i am facing similar issues elsewhere too ...

For ex : in my employees main page i want to display all the qualifications for each employee for which im doing :

<tbody>
<% @employees.each do |employee| %>
  <tr>
    <td><%= employee.emp_id %></td>
    <td><%= employee.emp_treasury_id %></td>
    <td><%= link_to employee.emp_full_name,employee_path(employee) %></td>
    <% @employee.qualifications.each do |qualification| %>
            <td><%= qualification.qualification_name.Qualification_name %></td>
    <% end %>
  </tr>
<% end %>

but i end up getting "undefined method `qualifications' for nil:NilClass" error once again ... Im trying a lot ... but still ...

Thanx and Sincere Regards

-Sky

Upvotes: 0

Views: 89

Answers (3)

abhijit
abhijit

Reputation: 1968

It should be

employee not @employee

Rest you use try or respond_to for being more safe. As you might not have run the migrations.

.respond_to?(:field) && model.try(:field)

Thanks

<% @employees.each do |employee| %>
  <tr>
    <td><%= employee.emp_id %></td>
    <td><%= employee.emp_treasury_id %></td>
    <td><%= link_to employee.emp_full_name,employee_path(employee) %></td>
    <% employee.qualifications.each do |qualification| %>
            <td><%= qualification.try(:qualification_name).try(:Qualification_name) %></td>
    <% end %>
  </tr>
<% end %>

Upvotes: 1

Sachin R
Sachin R

Reputation: 11876

Try this

<%= @employee.postings.last.try(:hospital).try(:hospital_name) || "N/A" %>

Upvotes: 1

jvnill
jvnill

Reputation: 29599

using try

<%= @employee.postings.last.try(:hospital).try(:hospital_name) %>

using if

<%= @employee.postings.last.hospital.hospital_name if @employee.postings.exists? && @employee.positings.last.hospital %>

Upvotes: 1

Related Questions