Table associations

First, thanks to everyone who replied to my pluralization question
from before!

Today I was trying to do what I think is called a “chained accessor”.
I have an “events” table and each event has one user. Instead of
seeing the id number for each event’s user, I’d rather display the
names of users instead. I tried to do this:

class Event < ActiveRecord::Base
belongs_to :user
end

class User < ActiveRecord::Base
has_many :events
end

in the event_controller.rb:
def list
@users = User.find(:all)
@events = Event.find(:all)
end

in the list.rhtml:
<% @events.each do |eachevent| %>

<%= link_to eachevent.action, :action => "show", :id => eachevent.id %> <%= eachevent.user.name %> <%= eachevent.whenit %> <% end %>

But I get an error saying “You have a nil object when you didn’t
expect it! The error occured while evaluating nil.name”

What am I doing wrong? Thanks in advance for all replies!

-Jason

Hey, i think in your controller, you just need

def list
@events = Event.find_all
end

then in your view,

<% @events.each {|event| %>

<%= event.user.name %>

<% } %>

if that still breaks, which it probly will, then you may just not have a
user associated with it.
you could add this to test:

<% unless event.user.name %>
eek, you dont even got no user associated with this event
<% end %>

then i’d check the table contents and make sure you have the right
values in there.

hope it helps,
d.

Jason F. wrote:

in the list.rhtml:
<% @events.each do |eachevent| %>

<%= link_to eachevent.action, :action => "show", :id => eachevent.id %> <%= eachevent.user.name %> <%= eachevent.whenit %> <% end %>

But I get an error saying “You have a nil object when you didn’t
expect it! The error occured while evaluating nil.name”

you could add this to test:

<% unless event.user.name %>
eek, you dont even got no user associated with this event
<% end %>

You’re still going to raise an exception here if an event doesn’t have a
user.

I think you meant to write:

<% unless event.user %>
eek, you dont even got no user associated with this event
<% end %>