Validates_numericality_of validates presence too

Hi,

I have table named ‘whatever’ which one of the column named ‘worker_id’,
type int (accept null), that is foreign key to table ‘worker’, column
‘id’ (primary key).

I have this model validation:
validates_numericality_of :duration, :worker_id, :number,
:cast_in_heater_order_letter_id

Because of some reason, I don’t define relationship between table
‘whatever’ and ‘worker_id’ using has_many or has_one. So I put value to
worker_id column manually.

I have this code:
if row[‘teknisi’] == ‘-1’ then
@element.#{@controller_varname}_jobs <<
#{@class_controller.to_s.gsub(/OrderLetter/, ‘’)}Job.new(:number =>
row[‘no’],
:job => row[‘pekerjaan’],
:duration => row[‘durasi’],
:predecessor => row[‘ketergantungan’])
else
@element.#{@controller_varname}_jobs <<
#{@class_controller.to_s.gsub(/OrderLetter/, ‘’)}Job.new(:number =>
row[‘no’],
:job => row[‘pekerjaan’],
:duration => row[‘durasi’],
:predecessor => row[‘ketergantungan’],
:worker_id => row[‘teknisi’])
end

If row[‘teknisi’] is ‘-1’, the code does not execute well, because in
validation, it fail (I check it using script/console). It complains
worker_id is not number type. So I have to remove :worker_id from model
validation to make the code execute well if row[‘teknisi’] is ‘-1’.

Does anybody know why validates_numericality_of enforce
validates_presence_of?

Thank you.

You must use the option :allow_nil => true in the
validates_numericality_of statement in order to allow empty values:

validates_numericality_of :duration, :worker_id, :number,
:cast_in_heater_order_letter_id, :allow_nil => true

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs