But that only lets you validate the date at the controller level. What
if you want to perform validation at the model level, and from what I
gather is the Rails way of doing things?
The point the previous posters have been making is that by the time the
date is available for validation in the model it has already been
coerced into a valid format by rails so any attempt to validate it will
succeed.
I’ve put together a simple form that contains among other things a
date_select:
<%= date_select(:user, :dob, :order => [:day, :month, :year],
:start_year => 1900, :end_year => Date.today.year) %>
In my controller I have some code to create a user entity from the
parameters posted up from the form, like so:
parameters: {“user”=>{“dob(1i)”=>“2006”, “dob(2i)”=>“2”,
“dob(3i)”=>“31”}}
@user = User.new(params[:user])
As if by magic Rails will convert dates like 31/02/2006 into 03/03/2006
so at the model level ‘user.dob’ => ‘03/03/2006’.
Are you supposed to refrain from constructing model objects using the
above technique when dates are involved?
regards,
Cathal.
Tom M. wrote:
On Jan 31, 2006, at 2:20 AM, rails nut wrote:
Tom M. wrote:
I just use the standard library’s date validation
within the model’s validate method.
–
– Tom M.
I can’t see anything for date validation in the rails book or the ruby
book. Can you tell me what you mean by ‘standard library date
validation’ please ?
Sorry for the long delay on this.
The talk of Rails returning dates that don’t match the
input rather surprised me. I’ve been working on tests
and backend work almost exclusively, so I wanted to
investigate this for myself completely before discussing
it further.
OK, I have a form that allows date input, and on submit
I get this in the logs:
Parameters: {“buyer”=>{“born_on(1i)”=>“1988”,“born_on
(2i)”=>“2”,“born_on(3i)”=>“31”}, “commit”=>“Create”}
I can access the buyer.born_on field, as you’ve been discussing, but
I can also access:
params[:buyer][‘born_on(1i)’] -> 1988
params[:buyer][‘born_on(2i)’] -> 2
params[:buyer][‘born_on(3i)’] -> 31
Which can be tested with this application.rb method:
def test_date(object,attribute)
Date.valid_civil?(params[object][attribute + ‘(1i)’].to_i,
params[object][attribute + ‘(2i)’].to_i,
params[object][attribute + ‘(3i)’].to_i)
end
by writing:
def valid
test_date(:buyer,‘born_on’)
end
–
– Tom M.