Validate attribute only if it present (only if user fill in it) - ruby-on-rails

I need validate some attributes ONLY if they are not empty.
For example the user may have a logo. If we try to load it - validation should work. If we simply update the user's data without the logo, validation must be skipped.
Now i have:
The form has a choice of two files. One - logo, second - avatar.
Both of this attributes is part of User model. In User model a have validation:
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 selected logo and avatar, we will have errors (our validation). I tryed change validation and add ":on => :update" like this:
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 user without selected logo and avatar, but if i try edit user and try upload only logo - i have validation errors of avatar. If i choose file for avatar and logo leave blank - i have validation errors for logo.
How i can run validation ony for attribute that I want to change?

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

Some validations accept the options :allow_blank => true or :allow_nil => true.
If this fails, use :if condition, like this:
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 encourage you to use allows. Much cleaner.

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

Related

validates in rails

I have a model with valid data; everything works.
In the form, I select as how to select the option I choose I want to be valid also 2 fields
validates_presence_of :is_ranking, :on => :update
validates :awards_count, :on => :update, :unless => :is_ranking == 1
Now as is_ranking == 1 to check again: awards_count
All sent from a form before being added to the database
How do I force rails to valid these two additional fields on the form I choose to rip options in select?
you should use symbol or string with :if and :unless
Try to replace condition with method
validates :awards_count, :on => :update, :unless => :is_ranking?
# You actually don't need that method in case your `is_ranking` field is `boolean`.
def is_ranking?
is_ranking == 1
end
Or with string
validates :awards_count, :on => :update, :unless => "is_ranking?"

In Rails, how can I only use validates_inclusion_of when the model is created, NOT every time it is updated?

I have an object, called Account, and there is a campaign source associated with every account. Currently, if the Account is updated, and there is no campaign source, you have to update the campaign source (the possible values of which are in a selectlist).
I know that validates_presence_of has an :on option, which allows you to specify :create, :update or :save, but validates_inclusion_of does not have this option, unfortunately. How can I get around this? Thanks.
Here is my code:
class Account < ActiveRecord::Base
validates_inclusion_of :campaign_source, :in => CampaignSource.list, :message => "^Please let us know how you heard about us"
Try
validates :campaign_source, :inclusion => { :in => CampaignSource.list },
:message => "^Please let us know how you heard about us",
:on => :create

Validation fails on ":on => :save"

I am using rails 3.0.10 and ruby 1.9.2p0
In my rails app I am trying to validate my model through a "validates_uniqueness_of"
In my model(label) there is field named as "name" and I want to validate it as:
validates_uniqueness_of :name, :scope => [:portal_id], :on => :save
Portal is another model in my app.
It validates perfectly when i use :on => :create or :update individually, but fails when i use :on => :save
any idea I want to validate on save, but AR validation fails.
As default all validations run before save.so no need to give :on => :save
Simply use
validates_uniqueness_of :name, :scope => [:portal_id]

validate email in rails after updating

In my user model, I have
validates :email, :presence=>true,
:format => { :with => email_regex },
:uniqueness => true
In my controller, I update the email if a user chooses to change it like this:
#user.update_attribute("email","#{#new_email}")
However, it doesn't throw an error if the format is not honored.
update_attribute does no validations. use
#user.update_attributes({ :email => #new_email })
instead.
I found out that update_attribute skips checking for validation but update_attributes doesn't! Interesting.
http://apidock.com/rails/ActiveRecord/Base/update_attributes

Rails Validation for users email - only want it to validate when a user signs up or updates email address

I have a User model with the usual attributes such as email and hashed_password etc. I want to write a validation that checks for the presence of an email address but only when
1) there isn't one stored in the database for this object (i.e. this is a new user signing up)
2) the user is trying to update their email address.
My current validations
validates_presence_of :email
validates_presence_of :email_confirmation
validates_confirmation_of :email
are obviously preventing me from updating any attributes. I thought of using
validates_presence_of :email , :if :email_validation_required?
def email_validation_required?
self.email.blank?
end
But that wont help with scenario 2 as it will return true because the user does have an password email address in the db.
I cant work out how i can limit it to just those 2 scenarios above.
Can anyone help?
I think EmFi is on to something. But I don't think the validates_presence_of :email should be holding you up. The email should always be present - if it is left blank in the form the parameter will not mess with your save of the user. If it is entered in the form, even for update, it should have an email_confirmation along for the ride.
Give this a try:
validates_presence_of :email
validates_presence_of :email_confirmation, :if => :email_changed?
validates_confirmation_of :email
you have two options. one is to use :on. by default, they are set to :on => :save, but you can do something like this this
validates_presence_of :email, :on => :create
or
validates_presence_of :email, :on => :update
the other options is to use :if, and then pass in a method name or a proc. so something like
validates_presence_of :email, :if => :should_validate
or
validates_presence_of :email, :if => Proc.new { |user| user.signup_stage > 2 }
Hope that helps :)
You want to use an :if clause on the validation that uses the ActiveRecord::Dirty methods:
validates_presence_of :email, :if => Proc.new { |user| user.email_changed?}
N.B. Only works in Rails 2.1 or later.

Resources