Setting a boolean to false in a before_create callback


#1

Has anyone ever had trouble doing this? Whenever I try to do so, it
doesn’t seem to work:

in my model:

  before_create :set_defaults

  def set_defaults
    self.submitted = false
  end

in my rspec test:

  it "Should set 'submitted' to false before a create" do
    @assignment = Assignment.new(:submitted => true)
    @assignment.save
    @assignment.submitted.should be_false
  end

and the result:

Assignment Should set 'submitted' to false before a create' FAILED
expected false, got true

#2

Does the object pass validation? before_create callbacks won’t run if
it doesn’t.

I’d recommend changing the middle line to @assignment.save.should
be_true or equivalent to check if the record is getting saved at all.

–Matt J.

On May 12, 8:14 pm, Gabriel S. removed_email_address@domain.invalid


#3

On 13 May 2009, at 18:07, Matt J. wrote:

Does the object pass validation? before_create callbacks won’t run if
it doesn’t.

I’d recommend changing the middle line to @assignment.save.should
be_true or equivalent to check if the record is getting saved at all.

Also, be careful as if a before_create evaluates to false (as your one
does) the create won’t actually happen.

Fred


#4

Gabriel S. wrote:

Also, is it just me because I’m too new, or is the
“before_validation_on_create” callback not talked about enough?

As me for me, I set my defaults in the migration (and hence the
database) rather than initializing attributes with callbacks. I don’t
know if that’s exactly the right way to do it, but it seems to work well
as far as I can tell.



t.boolean :bool_value, :default => false


#5

Also, be careful as if a before_create evaluates to false (as your one
does) the create won’t actually happen.

a-ha! thanks to both of you!

I had no validations on submitted because I was trying to isolate the
problem (but that doesn’t mean i didn’t want any), but indeed, it was
the before_create evaluating to false.

final version:

before_validation_on_create :set_defaults

def set_defaults
self.submitted = false
return (self.submitted == false)
end

Also, is it just me because I’m too new, or is the
“before_validation_on_create” callback not talked about enough?

Cheers,
-Gabe