date_select problem

Hi,

I'm entering two dates into a view through the date_select helper, the first relates to a field in the database, the second has been added to the model with attr_accessor. When the create action is invoked, it fails when trying to create a new object. Here's the code:

View

<% form_for(@cto) do |f| %>   <p>     <%= f.date_select :dayoff %>   </p>   <p>     <%= f.date_select :end_date %>   </p>   <p>     <%= f.submit "Create" %>   </p> <% end %>

Controller

  def create     @cto = Cto.new(params[:cto])       respond_to do |format|         if @cto.save           flash[:notice] = "Cto was successfully created.}"             format.html { redirect_to(@cto) }             format.xml { render :xml => @cto, :status => :created, :location => @cto }         else             format.html { render :action => "new" }             format.xml { render :xml => @cto.errors, :status => :unprocessable_entity }         end       end   end

Model

class Cto < ActiveRecord::Base

  attr_accessor :end_date

end

Error

You have a nil object when you didn't expect it! The error occurred while evaluating nil.klass

Parameters

{"commit"=>"Create", "authenticity_token"=>"1b2c46eed03c8154cc26d32fa8b01d6e4caa4490", "cto"=>{"end_date(3i)"=>"28", "dayoff(1i)"=>"2008", "dayoff(2i)"=>"8", "dayoff(3i)"=>"28", "end_date(1i)"=>"2008", "end_date(2i)"=>"8"}}

Any ideas? If I change the date_select to a select_date, the error stops, but then I don't have the data in my model.

Sorry for the long message, just thought the code would help.

Hi,

I'm entering two dates into a view through the date_select helper, the first relates to a field in the database, the second has been added to the model with attr_accessor. When the create action is invoked, it fails when trying to create a new object. Here's the code:

Error

You have a nil object when you didn't expect it! The error occurred while evaluating nil.klass

Parameters

{"commit"=>"Create", "authenticity_token"=>"1b2c46eed03c8154cc26d32fa8b01d6e4caa4490", "cto"=>{"end_date(3i)"=>"28", "dayoff(1i)"=>"2008", "dayoff(2i)"=>"8", "dayoff(3i)"=>"28", "end_date(1i)"=>"2008", "end_date(2i)"=>"8"}}

Any ideas? If I change the date_select to a select_date, the error stops, but then I don't have the data in my model.

Long version: This is due to the slightly magic way in which
date_select works. As you can see you get three parameters. The (1i),
(2i) etc.. suffices mean 'this one is the nth parameter to the
constructor and it's an integer'. Rails then looks at your model, sees
that dayoff is a date column and knows that it should creating a new
Date, passing the 3 2008,8 and 28 as arguments. It can't do this trick with end_date because it has no way of knowing
what kind of object it should be creating. Short version: use select_date (you'll have to take the appropriate
parameters and turn them into a date yourself.

Fred