Please log into your user account or create a new one
#35: validating date_select in rails
Solved!
If you use the date_select helper in Rails, setting all fields except for the year will result in MultiparameterAssignmentErrors. You can catch the exception, but it's kind of hard to catch it in a place where you can add errors to a model instance.
override assign_multiparameter_attributes
-
kueda on April 15, 2009, 11:41 PM UTC
I ended up overriding assign_multiparameter_attributes to look for empty fields. Obviously, this will break non-date multiparam assignments, but I'm hoping that will be ok in my case.
In my model:
In my model:
1 2 def assign_multiparameter_attributes(pairs) 3 pair_values = Hash[pairs].values 4 if pair_values.collect(&:blank?).include?(true) && 5 pair_values.collect(&:blank?).uniq.include?(false) 6 @incomplete_date = true 7 else 8 super(pairs) 9 end 10 end 11 12 def validate 13 if @incomplete_date 14 self.errors.add_to_base("The date you entered is incomplete!") 15 end 16 end
Think you've got a better solution? Help
kueda out by posting your solution
http://giantrobots.thoughtbot.com/2007/5/29/ruby-on-fails - found by
kueda on April 15, 2009, 11:42 PM UTC
Lists the many ways you could approach the problem. My solution was derived from some of the comments. Note that he ended up just not using date_select. Probably the better solution.
