0

I'm building a marketplace app in Rails 4. When entering products, sellers can enter a price and a saleprice. SalePrice is optional.

My current validations below check for values greater than 0. How do I add a validation for - saleprice must be at least 5% lower than price.

validates :price, numericality: {greater_than: 0}
validates :saleprice, numericality: {greater_than: 0}, :allow_blank => true

3 Answers 3

2

you can use custom validation

validate :saleprice_lower_than_price

def saleprice_lower_than_price
  if (saleprice != nil && saleprice > (price - (price * 0.05))
    errors.add(:saleprice, "Sale price should be 5% less than price")
  end
end
Sign up to request clarification or add additional context in comments.

Comments

0

You'll need to write your own custom validation method, there is a good explanation in the rails guides: http://guides.rubyonrails.org/active_record_validations.html#custom-methods

Comments

0

Just create a custom validation method

validate :saleprice_lower_than_price

def saleprice_lower_than_price
  (price - saleprice) > price * 0.05
end

Optionally you can add condition in this method to add errors to your object, like

errors.add(:saleprice, 'should be lower')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.