DhatchXIX DhatchXIX - 1 year ago 87
Ruby Question

undefined method `number' for nil:NilClass

I am having problems display an attribute in a belongs_to relationship. Lease belongs_to Unit. Unit has a column "number" in the db. When I try to display this attribute on the lease show page, it gives me an error of undefined method `number' for nil:NilClass. I feel like I'm doing something stupid and over looking it.


belongs_to :unit


has_many :leases


def show
@lease = Lease.find(params[:id])


<%= @lease.unit.number %>

If I change my show page code to @lease.unit_id it will show the id of the unit. Here is a pic of my data base showing the Unit_id.
enter image description here

Answer Source

Your model may have unit_id attribute, but how about units that does not have that record with id = 1 have You checked?

Quick (dirty) fix:

<%= @lease.unit.number unless @lease.unit.nil? %>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download