Topic: Action Controller: Exception caught.

okay I keep getting this error when I run this method.

[code error]You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occured while evaluating nil.each[/code]
okay it is a list of users with a form at the bottom to allow you to add a new user. the whole thing works fine. untill an error is thown by the a field not being entered. If I dont add the

<%= error_messages_for 'user' %>

its all fine. but I dont get the error messages.

okay these are the methods that are being used.
[code methods]def add_a_user
    @user = User.new(params[:user])
    @user.account_id = @account.id
    if @user.save
      flash[:notice] = "#{@user.username} Added"
      redirect_to :action => "list_users"
    else
      render_action 'list_users'
    end

  def list_users
    @userlist = User.account_users(@account.id)
  end[/code]
and the views
[code list_users view]
<table width="700">
    <tr>
        <td>UserName:</td><td>Email Address:</td><td></td><td></td><td></td>
    </tr>
<% for list in @userlist -%>
    <tr>
        <td><%= list.username %></td>
        <td><%= list.email_address %></td>
        <td><%= link_to "Delete", {:action => "delete_user", :id => list.id},
                                                              :confirm => "Are you sure you want to delete #{userlist.username}"%></td>
        <td><%= link_to("Suspend", :action => "suspend_user")%></td>
        <td><%= link_to("Edit", :action => "edit_user" )%></td>
    </tr>

<% end -%>

</table>
<hr>
<%= render_partial "add_a_user" %>
[/code]

[code and the partaial]
%= error_messages_for 'user' %>

<%= start_form_tag(:action => "add_a_user") %>

<table>
    <tr>
        <td colspan="4">Add a User</td>
    </tr>
    <tr>
        <td>UserName</td><td>Email Address</td><td>Authority</td><td></td>
    </tr>
    <tr>
        <td><%= text_field("user", "username", "size" => 20)%></td>
        <td><%= text_field("user", "email_address", "size" => 20)%></td>
        <td><i>member</i></td>
        <td><%= submit_tag(" ADD USER ")%></td>
    </tr>
</table>
<%= end_form_tag %>
[/code]

although it works without the error messages, I would like them there smile

--

Re: Action Controller: Exception caught.

I don't think the problem has anything to do with displaying the errors. The problem is happening when attempting to loop through the @userlist array after the form is submitted with an error in it. This is because that view is rendered, but the @userlist variable is not created in the add_a_user action. You need to create the @userlist there as well:

#...
else
  @userlist = User.account_users(@account.id)
  render_action 'list_users'
end

This leaves duplicate code, so I recommend moving it into a before filter or something.

Railscasts - Free Ruby on Rails Screencasts

Re: Action Controller: Exception caught.

big_smile bingo. thanks again ryanb

--