Tuesday, June 25, 2013

[Rails] Correct use of before_validation

I'm using Rails 3.2.13 with Ruby 2.0.0

I have a field in a form called "hours" which normally passes a
numerical value.

However, my users also want the option to pass time values, like
"01:15", "00:25", ":05", etc.

I've tried to allow for this sort of thing with the below code:

______
validates :hours, :presence => true, :numericality => { :greater_than
=> 0, :less_than => 12 }

before_validation do
STDOUT << 'Test'
self.hours = hours.scan( /(\d*):(\d*)/ ).map { |hrs, mins| hrs.to_f
+ ( mins.to_f / 60.0 ) }.first.round(4) if hours && hours =~ /:/
end
______

The problem I'm getting is that the validation doesn't appear to fire at
all.

When I input ":05", for example.

The form states that Hours is not a number.
I don't see "Test" in the server console.

The code converting from a time string into a float appears to work in
IRB.

--
Posted via http://www.ruby-forum.com/.

--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email to rubyonrails-talk+unsubscribe@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/rubyonrails-talk/9c071c83773d48d461fb4ba333ab588b%40ruby-forum.com.
For more options, visit https://groups.google.com/groups/opt_out.

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home


Real Estate