Forum: Ruby on Rails before_create question

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
38a8230ed3d5c685558b4f0aad3fc74b?d=identicon&s=25 Joe Van Dyk (Guest)
on 2005-12-30 07:39
(Received via mailing list)
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.
C64e63b70be7dfed8b0742540b8b27e5?d=identicon&s=25 Mark Reginald James (Guest)
on 2005-12-30 08:25
(Received via mailing list)
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.
38a8230ed3d5c685558b4f0aad3fc74b?d=identicon&s=25 Joe Van Dyk (Guest)
on 2005-12-30 10:48
(Received via mailing list)
On 12/29/05, Mark Reginald James <mrj@bigpond.net.au> wrote:
> > 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!
This topic is locked and can not be replied to.