On 24.02.2012, at 23:38, David M wrote:

How can I validate a date that is set with select boxes on the form, so I can raise an error when it's invalid?

The default behavior when an invalid date is entered is to add days to arrive to a valid date. For example: if 2012-31-06 is sent to the controller, the resulting date will be 2012-01-07

How can I stop this behavior and raise an error?

I'm using the date_select(object_name, method, options = {}, html_options = {})method in the view.
Interesting question.

In the case when date_select helper used, it automatically generates parameter keys:
'date(1i)' - year
'date(2i)' - month
'date(3i)' - day

When ActiveRecord model receives these parameters, Date object will be generated and assigned to a corresponding model's attribute. In this process, there is its clever logic: when values of these parameters aren't clearly 'crazy', Date object will be generated correctly without attention to the minor errors in the number of days (28, 30 or 31) without any validation errors.

To avoid this integrated logic you can put down your own model's accessors for 'date(1i)', 'date(2i)', 'date(3i)' mass-assignment parameters and appropriate custom validator. Or you can hack ActiveRecord::MultiparameterAssignment stack to escape its logic. Both are unaesthetic, unclean approaches from all points of view.

Instead of 'date_select', you can use 'select_date' (render just the tag), in this case date parameters will be named as you want. Just write the accessors and attribute assignment logic, then put the custom validator and this is it.

As for me, I completely gave up date_helper and other selectors, and began to use strings for dates in a form, adding to their Jquery Date selector plugin. Much more convenient and simpler.



--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to rubyonrails-talk+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en.

Search Discussions

Discussion Posts

Previous

Follow ups

Related Discussions

Discussion Navigation
viewthread | post
posts ‹ prev | 2 of 4 | next ›
Discussion Overview
grouprubyonrails-talk @
categoriesrubyonrails
postedFeb 24, '12 at 7:39p
activeFeb 24, '12 at 9:14p
posts4
users3
websiterubyonrails.org
irc#RubyOnRails

3 users in discussion

Valery Kvon: 2 posts Bob Smith: 1 post David M: 1 post

People

Translate

site design / logo © 2022 Grokbase