Class User
before_save :set_searchable
def set_searchable
self.searchable = true if self.status == :active
end
end
>> u = User.last
>> u.save
false
u.save always return false. If i remove the before_save it works also if i give a return true in before_save it works
so do i need to give return statements in before_save ? will ActiveRecord saves an object if the before_save returns false ?
Where can i see a full documentation regarding callbacks and its workflow .
Thanks in advance
No, you don't need to return true from Rails callbacks. You can return nothing at all, or true, or 3.141592, and it will still be saved. The only thing that matters is if you return false, and this only applies prior to Rails 5. Returning false would cancel saving prior to Rails 5. Returning true never had any effect.
For Rails 5+, the new way to block the update is to throw an exception:
throw(:abort)
. . This is more intuitive and less error-prone. The return value has no effect on whether it will save, unless you configure legacy behaviour.It's valid - and imo good DRY practice - to just get on with your business and not return anything at all; just be sure to avoid accidentally returning false implicitly if using earlier Rails. For example:
The gotcha here is that you might forget some "procedural" type functions will return a boolean as a kind of status code or simply because the implementation happens to end with a boolean as a side effect. You might think you're mutating a string or something, but end up accidentally vetoing the callback. So while I think it's usually too noisy to explicitly return from callbacks, you do need to take care with implicit returns. One reason people advocated returning true was to guard against this gotcha.
Another cleaner way to set boolean columns without
return
is to usetap
The documentation say
BUT
you might want to check this out ( I have tested this myself and the issue is 100% authentic)
Plus also there is bug related to before_save you might want to know check the comment over here
As said in the comment it is observed sometimes.
Whatever you do just be aware of that there are some issues with rails callback. This would save your time when you ran into one of those
From: http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html
So, yes.