Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call before_update if an attribute is filled

What is the way to call the before_update trigger only if a particular attribute is filled?

Here is a part of my code:

before_update { self.gravatar = gravatar.downcase }

validates :gravatar, :on => :update, length: { maximum: 128 },
                    format: { with: VALID_GRAVATAR_REGEX }, 
                    allow_blank: true

Indeed I want to call the downcase function on the attribute only if this one is filled in the edit form.

I currently have this following error:

undefined method `downcase' for nil:NilClass

Which is logical.

like image 439
gaetanm Avatar asked Nov 23 '25 11:11

gaetanm


1 Answers

Like that ? before_update { self.gravatar = gravatar.downcase if gravatar.present? }

like image 83
Ugo Mare Avatar answered Nov 25 '25 02:11

Ugo Mare



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!