I’m trying to assign a parent foreign key value using
collection_select from my child “new” form. The problem I’m having is
if I do not make a selection, I get the following error instead of the
Rails validates_presence_of error:
You have a nil object when you didn’t expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.map
If I make a selection, everything works just fine. What do I need to
do to get the Rails validationvalidates_presence_of error?
Here’s the code:
MODEL
class Client < ActiveRecord::Base
has_many :programs
validates_presence_of :eid, :name
end
class Program < ActiveRecord::Base
belongs_to :client
validates_presence_of :client_id
validates_associated :client
end
CONTROLLERS
def new
@program = Program.new
@clients = Client.find(:all, :order=>“name”)
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => @program }
end
end
def create
@program = Program.new(params[:program])
respond_to do |format|
if @program.save
flash[:notice] = 'Program was successfully created.'
format.html { redirect_to(@program) }
format.xml { render :xml => @program, :status
=> :created, :location => @program }
else
format.html { render :action => “new” }
format.xml { render :xml => @program.errors, :status
=> :unprocessable_entity }
end
end
end
VIIEW
<%=
collection_select(‘program’,
‘client_id’,
@clients,
:id,
:name,
{ :include_blank => true }
)
%>
Thx for the assistance!