Serguei Cambour
2013-Mar-26 14:24 UTC
nested forms: use validate :some_method works in update mode only
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
--
You received this message because you are subscribed to the Google Groups
"Ruby on Rails: Talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to
rubyonrails-talk+unsubscribe-/JYPxA39Uh5TLH3MbocFF+G/Ez6ZCGd0@public.gmane.org
To post to this group, send email to
rubyonrails-talk-/JYPxA39Uh5TLH3MbocFF+G/Ez6ZCGd0@public.gmane.org
To view this discussion on the web visit
https://groups.google.com/d/msg/rubyonrails-talk/-/nx-_1cuViuoJ.
For more options, visit https://groups.google.com/groups/opt_out.
Possibly Parallel Threads
- How to use group in nested associations
- fields_for with accepts_nested_attributes: how to pass a value to a label
- accepts_nested_attributes: undefined method 'association'_attributes
- validates presence of foreign key fails in nested form
- search engine, select the selected option
