I have a Company class:
class Company < ActiveRecord::Base
validates :name, :presence => true
has_many :employees
end
and an Employee Class where the employee can only be associated with one company:
class Employee < ActiveRecord::Base
validates :lastName, :presence => true
belongs_to :company
validates :company, :presence => true
end
When I’m listing the employees,
<% @employees.each do |employee| %>
<tr>
<td><%= employee.firstName %></td> <- works
<td><%= employee.lastName %></td> <- works
<td><%= employee.company.name %></td> <- Get an 'undefined method `name' for nil:NilClass' error
</tr>
<% end %>
I thought the employees company was eagerly loaded and I can therefore access the association directly in the object, or is my syntax wrong?
Any help would be appreciated
I can think of two scenarios:
company_id = NULL.company_id = IDbut the company with this id does not exist anymore.In any case it’s trivial to check in the console the offending object(s):
Employee.reject(&:company).