I have a strange behavior when validating a record in a nested form. The association collection is empty when creating a new record and the validation does not catch the error. But when updating the same record the validation gets it right but continues to catch the error even after modifying the needed attribute value to make it pass.
Here is the model:
#timesheet.rb
class Timesheet < ActiveRecord::Base attr_accessible :status, :user_id, :start_date, :end_date, :activities_attributes
SUBMITTED = ‘Submitted’ APPROUVED = ‘Approuved’ REJECTED = ‘Rejected’
STATUS_VALUES = [SUBMITTED, APPROUVED, REJECTED] belongs_to :user has_many :activities, dependent: :destroy, inverse_of: :timesheet has_many :time_entries, through: :activities accepts_nested_attributes_for :activities, allow_destroy: true
validates :user_id, presence: true validates :status, presence: true, inclusion: {in: STATUS_VALUES} validate :maximum_worktime_per_day
after_update :check_an_activity_present
after_initialize :init_working_week
… private def maximum_worktime_per_day time_entries_by_date = time_entries.group_by(&:workdate) time_entries_by_date.each do |key, value| errors[:base] << “Maximum daily time should not exceed 1 day” if value.map(&:worktime).inject(:+) > 1 break end end
As I could see the output in the console, when creating a new record, the hash ‘ime_entries_by_date’ in the validation method is empty, that’s why the record is saved without problems even if the worktime exceeds the validation value of 1 day. When updating the same record, the validation method catches well the error but does not refresh the hash values even after I modify the work time values to make it pass. Any idea how to fix that?
Thank you