I have the following models: User, Registration, Event. User has_many Registration, Event has_many Registration, and Registration belongs_to User and Registration. So far, so good. There''s a registration deadline on a Event though, a few days before the Event occurs. So, I have this: class Registration < AR def before_create errors.add_to_base("Registration deadline has passed") unless event.can_still_register? end end The weird thing is, if the registration deadline has passed, the error gets added to the registration object, and calling save! throws no exception, but the registration object doesn''t get saved. So, this test code throws no exception: event = TrainingEvent.new :start_date => 19.days.from_now, :end_date => 22.days.from_now, :capacity => 10 reg = Registration.create :training_event => event, :user => @bob, :role => @community_director, :program_number => ''asdf'' assert_equal reg.errors.on(:base), ''Registration deadline has passed'' reg.save! I''m asserting that errors exist, but save! doesn''t throw an exception. But the registration doesn''t seem to be saved.
Joe Van Dyk wrote:> class Registration < AR > def before_create > errors.add_to_base("Registration deadline has passed") unless > event.can_still_register? > end > end > > The weird thing is, if the registration deadline has passed, the error > gets added to the registration object, and calling save! throws no > exception, but the registration object doesn''t get saved.before_create is too late in the chain to add errors that affect the validation check. You''ll need to rename to validate_on_create. -- We develop, watch us RoR, in numbers too big to ignore.
On 12/29/05, Mark Reginald James <mrj-bzGI/hKkdgQnC9Muvcwxkw@public.gmane.org> wrote:> Joe Van Dyk wrote: > > > class Registration < AR > > def before_create > > errors.add_to_base("Registration deadline has passed") unless > > event.can_still_register? > > end > > end > > > > The weird thing is, if the registration deadline has passed, the error > > gets added to the registration object, and calling save! throws no > > exception, but the registration object doesn''t get saved. > > before_create is too late in the chain to add errors that affect the > validation check. You''ll need to rename to validate_on_create.Ah, thanks. Now my tests pass!