Mark Kadlec
Mark Kadlec

Reputation: 8440

How to show an association value in a view?

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

Upvotes: 1

Views: 43

Answers (2)

tokland
tokland

Reputation: 67850

I can think of two scenarios:

  1. company_id = NULL.

  2. company_id = ID but 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).

Upvotes: 2

Simone
Simone

Reputation: 21262

Since an employee belongs to a company, you should load the employees from the company itself. Something like:

class EmployeeController < ApplicationController

  def index
    @employees = @company.employees
    ...
  end
  ...
end

Upvotes: 0

Related Questions