Question

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?

Was it helpful?

Solution

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 %>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top