Reputation: 97
I am sorry if similar question have been asked already I couldn't find anything identical.
Thus, can someone tell me why before_save
especially conditional one can to be considered bad, please?
before_save :something, if: Proc.new { self.abc == 'hello' }
Therefore I understand why validation sometimes fits much better, however what I don't understand is why some people think that callbacks can to be a bad thing to use and they force you to write only validations but never make them conditional.
I personally think that there's can be far larger problem because this change can affect already existing entries and so it's okay to implement conditional validator or to provide if
for before_save
if you plan to modify data only in certain case. Why some people think it's not okay? Could someone help me with that?
Thank you very much!
Upvotes: 0
Views: 533
Reputation: 4561
Using callbacks are standard Rails practice! When used appropriately they are great DRY helpers when it comes to maintaining data-integrity. Callbacks are heavily used for data-formatting user input (like removing spaces or dashes from a cellphone number field) where responding back with an error via a validation would just frustrate the user. Use validations to handle cases you can't predict or data that would be otherwise unpredictable and callbacks elsewhere (like downcasing an email before saving).
Upvotes: 0
Reputation: 6603
I think that the only disadvantage of before_save
or before_validation
is when it is not understood or used properly
before_save
and before_validation
are different, and that a developer should understood that some callbacks are meant to be used as before_save
, and some, as before_validation
Aside from these, I do not see any problem with before_save
as it can potentially clean and break down the logic of the code, and allows reusability especially if you have subclasses of the model.
Just my immediate thoughts on the matter...
Upvotes: 1