jared
jared

Reputation: 241

Rails has_many error: undefined method ` ' for nil:NilClass

I kept receiving the above error and have spent days digging through posts and documentation trying to find the cause.

The app I'm buildings records fuel usage. The word repairer is in reference to a supplier in its own model with attributes like Rep_Name (Name) Address, Phone etc. Initially for scaffolding purposes, only repairer_id was used and everything worked fine. The issue came when trying to call the rep_name from the repairer model. (I even tried renaming the field to rep_name instead of name to solve the issue)

    undefined method `rep_name' for nil:NilClass

Extracted source (around line #38):

35:             <td><%= f.litres %></td>
36:             <td><%= f.cost %></td>
37:             <td><%= f.tax %></td>
38:             <td><%= f.repairer.rep_name%></td>
39:             <td><%= f.fuel_type %></td>
40:             <td class= "actions">
41:                 <%= link_to("Show", {:action => 'show', :id =>  f.id}, :class => 'btn btn-info') %>

Upvotes: 0

Views: 344

Answers (2)

shweta
shweta

Reputation: 8169

replace <%= f.repairer.rep_name%> with

<%= f.repairer.blank? ? "" : f.repairer.rep_name %>

Upvotes: 1

jared
jared

Reputation: 241

The cause of this was actually dirty data in the database. I had several fuel records where the repairer_id was null.

I deleted these records and the issued is resolved.

Upvotes: 0

Related Questions