Ruby on Rails | Screencasts | Download | Documentation | Weblog | Community | Source

Ticket #7377 (new enhancement)

Opened 1 year ago

Last modified 5 months ago

[PATCH] Doc update to clarify callback execution order

Reported by: cpisto Assigned to: core
Priority: normal Milestone: 1.2.7
Component: ActiveRecord Version: edge
Severity: normal Keywords: docs
Cc:

Description

before_save (and _create/_update friends) is not called before validations are run (contrary to documentation)


create table test (
  id serial primary key,
  value text
);

class Test < ActiveRecord::Base
  validates_format_of :value, :with => /^[A-Z]+$/,
    if => proc { |record| record.value != nil }

  before_save { |record| record.value = nil if record.value == '' }
end

test = Test.new
test.value = ''
test.save!

=> value is invalid


Workaround is to put code in before_validation callback instead of before_save.

Attachments

callbacks_doc.diff (6.4 kB) - added by smeade on 01/25/07 20:56:56.
callbacks_doc.diff

Change History

01/25/07 20:12:09 changed by smeade

i see cpisto's point. The example save call has it right:

  # * (-) save
  # * (-) valid?
  # * (1) before_validation
  # * (2) before_validation_on_create
  # * (-) validate
  # * (-) validate_on_create
  # * (3) after_validation
  # * (4) after_validation_on_create
  # * (5) before_save
  # * (6) before_create
  # * (-) create
  # * (7) after_create
  # * (8) after_save

but the description for each method is misleading.

e.g.

before_save - 
    # Is called _before_ Base.save (regardless of whether it's a create or update save).
before_validation -
    # Is called _before_ Validations.validate (which is part of the Base.save call

If before_save is called before Base.save and validations are part of Base.save, then you would expect before_save to happen before the validations. I'm not sure what the right doc patch is though?

How about updating _before_ Base.save to "before a record is saved or updated"?

01/25/07 20:56:56 changed by smeade

  • attachment callbacks_doc.diff added.

callbacks_doc.diff

01/25/07 20:58:41 changed by smeade

  • version changed from 1.2.0 to edge.
  • type changed from defect to enhancement.
  • summary changed from before_save is not called before validations are run to [PATCH] Doc update to clarify callback execution order.

callbacks.rb doc updates to further clarify callback execution order

03/10/07 02:12:59 changed by josh

  • keywords set to docs.

12/05/07 22:00:47 changed by marcel

I like the clarifications you've made here but sprinkling "(See Callbacks for the order in which callbacks are executed)" all over the place feels like a DRY violation :)