Getting started with Rails and I’m stuck with a block operation. I want to loop through a model and update integer values for a new field by calculating difference between two datetime fields. Doing this in the console:
MyModel.all.each do |m|
m.new_integer_field = m.existing_datetime_field - m.parent_object.existing_datetime_field
m.save!
end
The result is
NoMethodError: undefined method `-' for nil:NilClass
It works on one record if I do:
m = MyModel.find(1)
m.new_integer_field = m.existing_datetime_field - m.parent_object.existing_datetime_field
m.save
I guess it’s a basic syntax thing, but couldn’t find obvious explanations. Grateful to get some pointers forward.
The m.existing_datetime_field in one of the instances was nil and therefore the operation didn’t work. You need to check for nil values if not sure: