views:

229

answers:

1

I'm having a problem in my Ruby on Rails app with a model where a belongs_to relationship keeps ending up being nil.

Given the following models:

 class Chassis < ActiveRecord::Base
   belongs_to :model
   belongs_to :chassis_size
 end

 class Model < ActiveRecord::Base
    has_many :chassis
 end

 class ChassisSize < ActiveRecord::Base
    has_many :chassis
 end

Now, I would expect in my chassis index view I would see both the model and the chassis_size data given:

 <% @chassis.each do |chassis| %>
    <%= chassis.id %><br />
    <%= chassis.model.name %><br />
    <%= chassis.chassis_size.size %><br />
 <% end %>

But I get an error that the chassis_size.size is nil:

 You have a nil object when you didn't expect it!
 You might have expected an instance of Array.
 The error occurred while evaluating nil.size    

Looking at the data in the database, everything appears to be correct.

I am not sure why model works but chassis_size does not. What am I missing? Why doesn't the chassis_size data appear to load?

A: 

Is size a column in your chassis_sizes table?

If so, this is a reserved word in ruby, as it is the method for returning the length of an array.

Does every chassis have a chassis_size? Try this:

<% @chassis.each do |chassis| %>
    <%= chassis.id %><br />
    <%= chassis.model.name %><br />
    <% if chassis.chassis_size %>
        <%= chassis.chassis_size.description %>
    <% else %>
        No chassis_size exists for this chassis
    <% end %><br />
 <% end %>
DanSingerman
Yes, size is a column. I accept that I should rename it to something else...BUT... I have a description column on that table too, and using that results in an "undefined method `description' for nil:NilClass" error
y0mbo
Sure enough, I missed a key in the migration and didn't see the NULL values when I scrolled through the data. Thanks!
y0mbo
I'm having a similar problem...but I'm pretty sure the data is correct....what do you mean you "missed a key"? Do you mean that some of the chassis are Null? Or some of their size is null? For me, if I ask the class of the object it belongs to, it works, but if I ask for an attribute of that object, it says it's a nill class.
Jenny