I have an integer column int(10) in a MySQL database. I am trying to use Rails validation to ensure that only integers get to this column. I wrote my validation rules as follows:
class Task < ApplicationRecord
validates :name, format: { with: /\A[a-zA-Z]+\z/, message: "only allows letters" }, length: { minimum: 2, maximum: 30 }, if: :name?
validates :period, format: { with: /\A[0-9]+\z/, message: "Invalid period." }, if: :period?
end
Then I wrote a test case as follows:
require 'test_helper'
class TasksControllerTest < ActionDispatch::IntegrationTest
test "Reject invalid period" do
post '/tasks', params: { period: "gfghd" }, xhr: true
assert_includes( @response.body, "error")
end
test "Reject invalid name" do
post '/tasks', params: { name: "646rttr7" }, xhr: true
assert_includes( @response.body, "error")
end
end
The issue is that the validation fails to reject the invalid period and the period column gets filled with a zero value and I don't know where the zero comes from. I have logged the content of the period value before it gets to the validation and it is not zero. Secondly, I don't understand why the database is being hit when the period value shouldn't pass the format regex as specified. I also like to mention that the validation for the name input (validates :name, ...
) works as expected. Please I need help to explain why the period input validation (validates :period, ...
) is not working and why the period column is filled with zero.
Aucun commentaire:
Enregistrer un commentaire