omar
omar

Reputation: 55

Displaying values from another model in view

I'm new to this and have an easy question I'm sure. I have 2 models, customers (has many jobs) and jobs (belongs to customers). I have a view which displays job details. I want to select data from the customer, but am getting an error.

Index action in jobs controller:

@jobs = Job.all (NB have also tried @jobs = Job.includes(:customer).all)

In my view:

<% @jobs.each do |job| %>
  ...
  <td><% job.customer.surname %></td>`

But I get the following error:

undefined method `surname' for nil:NilClass

What am I doing wrong please?

Upvotes: 1

Views: 56

Answers (1)

rmosolgo
rmosolgo

Reputation: 1874

Although Job belongs to Customer, it's possible that a given job.customer may be nil!

First, you can check this in your view:

<% jobs.each do |job| %> 
  <% if job.customer.blank? %>
    <!-- debugging info: -->
    <p>Oops, this Job doesn't have a customer</p>
    <p>customer_id is <%= job.customer_id.inspect %>)</p>
  <% else %>
    <p><%= job.customer.surname %></p>
  <% end %>
<% end %>

If it turns out that some Jobs don't have Customers, there might be something wrong in another part of the app. There are few possibilities:

  • jobs#create is not assigning the customer to the job.

    To prevent this, edit Job and add validates :customer, presence: true.

  • job.customer_id may contain an invalid foreign key (ie, job.customer_id is present, but there is no Customer whose id is job.customer_id).

    To prevent this, inside Customer, add has_many :jobs, dependent: :destroy to make sure that all jobs are destroyed when the customer is destroyed.

Upvotes: 1

Related Questions