views:

87

answers:

1

I have a 1:1 has_one / belongs_to relationship between users and registrations. One user has one registration.

When I try to iterate through users in a view and display their registration info (source to follow), I get the following error:

ActionView::TemplateError: You have a nil object when you didn't expect it! The error occurred while evaluating nil.registration_code

Here's the offending view code:

<% @users.each do |user| %>
<%= user.registration.registration_code %>
<% end %>

In my users_controller.rb:

def users_registration_codes
  @users = User.find(:all)
end
+3  A: 

The likely issue here is that you're finding a particular User without an associated Registration - i.e. it's not that user == nil, but that user.registration == nil so it complains when you try to call registration_code() on the non-existent associated registration object

Try

<% @users.each do |user| %>
  <%= user.registration.registration_code if user.registration %>
<% end %>
mylescarrick
That settles it.
Swanand