Check the attribute only if it is present (only if the user has filled it)

I need to check some attributes ONLY if they are not empty.

For example, a user may have a logo. If we try to download it, validation should work. If we simply update user data without a logo, validation should be skipped.

Now I have:

The form has a choice of two files. One is a logo, the second is an avatar. Both of these attributes are part of the User model. User model a has a check:

validates_preference_of :logo_file_name, :message=>I18n.t("...") validates_format_of :logo_file_name, :with=>/\.(jpeg|jpg|png|gif)$/i, :message=> I18n.t("...") validates_preference_of :avatar_file_name, :message=>I18n.t("...") validates_format_of :avatar_file_name, :with=>/\.(jpeg|jpg|png|gif)$/i, :message=> I18n.t("...") 

In this case, if we try to create a new user without the selected logo and avatar, we will have errors (our check). I tried checking for changes and added ": on =>: update" as follows:

 validates_preference_of :logo_file_name, :message=>I18n.t("..."), :on => :update validates_format_of :logo_file_name, :with=>/\.(jpeg|jpg|png|gif)$/i, :message=> I18n.t("..."), :on => :update validates_preference_of :avatar_file_name, :message=>I18n.t("..."), :on => :update validates_format_of :avatar_file_name, :with=>/\.(jpeg|jpg|png|gif)$/i, :message=> I18n.t("..."), :on => :update 

Now I can create a user without the selected logo and avatar, but if I try to edit the user and try to upload only the logo, I have avatar verification errors. If I select a file for the avatar and logo, leave it blank - I have validation errors for the logo.

How can I run an ony check for the attribute that I want to change?

+47
ruby validation ruby-on-rails
Oct 23 '11 at 18:08
source share
3 answers

Add :allow_blank => true and it should do what you want.

+106
Oct 23 '11 at 18:15
source share

Some checks accept parameters :allow_blank => true or :allow_nil => true .

If this fails, use: if condition, for example:

 validates_format_of :avatar_file_name, :with=>/\.(jpeg|jpg|png|gif)$/i, :message=> I18n.t("..."), :on => :update, :if => lambda{ |object| object.avatar_file_name.present? } 

But I urge you to use permissions. Much cleaner.

+8
Oct 23 2018-11-23T00:
source share

Maybe :if => lambda {|attr| attr.present?} :if => lambda {|attr| attr.present?} will help?

+4
Oct 23 2018-11-21T00:
source share



All Articles