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?
ruby validation ruby-on-rails
prosto.vint Oct 23 '11 at 18:08 2011-10-23 18:08
source share