Hi everyone!
I’m new to rails and have been playing around a bit. Unfortunately, I
seem to be a bit stuck at the moment. Since I’m just playing around,
I’m using a dynamic scaffold. In my model file (which is tied to a
database table), I have the following line:
validates_format_of :grade, :with => /^[0-9]+$/, :message => ‘should
be zero or a positive integer’
‘grade’ is an int(6) column in my table. What I would expect is that
if I enter some random letters such as “asdas” in a form, then the
string should be considered invalid and should throw an error.
However, this does not occur. Instead, the form saves the data into
the table with a value of 0.
During my tests, I changed [0-9] to [1-9]. On doing so, “asdas” would
not be accepted anymore, but “123as” would. “123” would be saved to
the database.
Perhaps my understanding of the above regular expression is wrong? It
is my first time using regexp. However, I wrote a little test program
in ruby:
tst = Array.new
tst[0] = ‘letters’
tst[1] = ‘123let’
tst[2] = ‘let123’
tst[3] = ‘1234’
tst[4] = ‘5’
tst[6] = ‘1.5’
tst.each do |type|
puts “#{type}\n” if type =~ /^[0-9]+$/
end
As I expect, only 1234 and 5 are printed. It seems to work as expected
in this little program, but not during validation.
Any help/suggestions would be greatly appreciated!