DhatchXIX DhatchXIX - 2 months ago 6
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.

lease.rb

belongs_to :unit


unit.rb

has_many :leases


leases_controller.rb

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


views/leases/show.html.erb

<%= @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

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? %>