Reputation: 19929
I have an Item object that has a boolean value called has_instore_image that when set in a before_save method must be set to 0 rather than false. Is there a reason why this is so? Is this the expected behavior? I'm using Rails 3.2.19.
code:
class Item < ActiveRecord::Base
attr_accessible :has_instore_image
before_save :set_has_instore_image
def set_has_instore_image
if self.instore_images.count>0
self.has_instore_image=true
else
self.has_instore_image=0
#self.has_instore_image=false
end
end
Upvotes: 1
Views: 43
Reputation: 1500
From the Rails docs on callbacks:
If a before_* callback returns false, all the later callbacks and the associated action are cancelled.
So what happens is that, as the last expression of your callback evaluates to false
, then the callback chain is stopped and the save
action fails.
You can remedy it like this:
def set_has_instore_image
if self.instore_images.count>0
self.has_instore_image=true
else
self.has_instore_image=false
end
true
end
In fact, it's considered good practice to end all your before_*
callback definitions returning true
to avoid this very same problem.
Upvotes: 2