Reputation: 5073
I have the below validations for one of my models. The goal is to validate presence of first_name, last_name, and shop. Then after (but still before validation), I want to run my custom validation :status.
validates_presence_of :first_name
validates_presence_of :last_name
validates_presence_of :shop
validate :status, :on => :create
def status
do stuff with first_name and last_name
end
But it appears that :status is running before the other validations, so I am getting errors for nil first_name etc. How can I correct this?
Upvotes: 1
Views: 252
Reputation: 5105
I will try to help. If status
is a field in your table, you have to change the custom validate name. For instance
validates_presence_of :first_name
validates_presence_of :last_name
validates_presence_of :shop
validate :check_status, :on => :create
def check_status
if first_name.present? && last_name.present? && shop.present?
do stuff with first_name and last_name
errors.add(:status, "you message here.") // if you need a error message
end
end
For more information here custom validation. Hopefully it can help you
Upvotes: 0
Reputation: 34347
If you don't want your custom validation to run if the other validations have come back as invalid, do this:
def status
return if errors.present?
do stuff with first_name and last_name
end
Upvotes: 1