Hi, I’ve been trying to get this to work all night. I’ve made some
progress by reading other posts, but I’m stuck now and can’t figure out
what I am doing wrong.
I have two tables: application_users and user_types. In my
application_users table I have a field named “user_type_id”. At first,
I thought if I set up the foreign key with the correct names, it would
automatically appear in my “new” form, but I got past that issue.
My application_user model looks like this:
class ApplicationUser < ActiveRecord::Base
validates_presence_of :first_name, :last_name, :user_type_id,
My user_type model looks like this:
class UserType < ActiveRecord::Base
In my controller, my new method looks like this:
@application_user = ApplicationUser.new
@user_types = UserType.find_all
And I modified the new.rhtml view to contain this select list:
<% @user_types.each do |user_type| %> <%= user_type.user_type %> <% end %>
The select list fills with the data from my user_types table, but when I
submit the form I get the famous “nil object” error under “NoMethodError
in Admin#create”. The extracted source shows my code for the select
list in new.rhtml, specifically the “<% @user_types.each do |user_type|
My create method in my controller looks correct to me:
@application_user = ApplicationUser.new(params[:application_user])
flash[:notice] = ‘User was successfully created.’
redirect_to :action => ‘list’
render :action => ‘new’
I figured that there was some problem with my validation and it was
dying when it got sent back to the new form. I commented out the
validation and the form worked correctly. But if I put back the
validation, even just testing the presence of one field, and I don’t
fill out that field, I get the same error.
It’s obvious to me that the problem occurs when the application_user
object can’t be saved, and it gets sent back to the form where the
user_types object is now nil. But I don’t understand why. It seems
that when “application_user.save” fails, it goes to “render :action =>
‘new’” where @user_types should be initialized. The new method works
the first time I hit the form, why does it not work when it is called
from the create method?
Thanks for any help you can give me - this is driving me crazy.