On Sat, 3 Dec 2005, Nick S. wrote:
their is an error display it. So in my model I have tried:
But this doesn’t work, because I can’t access the values inside start_date
in the model. I get errors like that start_date is multiparameter . I know
that, but I can’t get to the values of the parameters. Hope somebody can
help.
say you have a table like:
create table moments (
id serial,
moment timestamp
);
and a controller like this:
[ahoward@localhost date_validation]$ cat
app/controllers/moment_controller.rb
class MomentController < ApplicationController
scaffold :moment
end
then a model like this will solve your problem
[ahoward@localhost date_validation]$ cat app/models/moment.rb
class ::Time
class << self
def normalized? t, values
tvalues = %w(year month day hour min sec usec).map{|m| t.send
m}
values.zip(tvalues){|vin,vout| return true if vin != vout}
return false
end
%w( local mktime gm utc ).each do |method|
eval <<-code
alias org#{ method }_ #{ method }
def #{ method }(*a, &b)
t = org#{ method }_(*a, &b)
t.instance_eval{@original_arguments = a}
t.instance_eval{@normalized = self.class.normalized? self,
a}
t
end
code
end
end
attr_reader ‘normalized’
alias_method ‘normalized?’, ‘normalized’
attr_reader ‘original_arguments’
end
class Moment < ActiveRecord::Base
protected
def validate *a, &b
t = moment
if t.nil? or t.normalized?
values = t.original_arguments
errors.add self.class.to_s, “bad time from
<#{values.inspect}>”
end
super
end
end
though you’d want to put the Time code somewhere else in practice…
an attempt to enter Feb 31st on my system results in an error page that
looks like
Editing moment
1 error prohibited this moment from being saved
There were problems with the following fields:
* Moment bad time from <[2005, 2, 31, 11, 48]>
i’ve posted this fix in the past but, for some reason, there was not
much
interest. read this thread for more info:
http://wrath.rubyonrails.org/pipermail/rails/2005-March/004619.html
this technique could easily be used to make a nice time/date validator
and is,
in fact, extensible for any multi-param rails object: the approach is
always
the same - try ctor, munge inputs if required, remember the original
arguments
for later access in validation.
kind regards.
-a
===============================================================================
| ara [dot] t [dot] howard [at] noaa [dot] gov
| all happiness comes from the desire for others to be happy. all misery
| comes from the desire for oneself to be happy.
| – bodhicaryavatara