I'm trying to create a condition in which the attribute 'one' is zero and the attribute 'two' is one, then a model is not valid. But when I make:
Model.create(:one => 1, :two => 0).valid?
The unit test returns true
! Why?
validates :one, :two, :presence => true, :if => :if condition_testing?
def condition_testing?
!(one == 0 && two == 1)
end
Validations are used to ensure that only valid data is saved into your database. For example, it may be important to your application to ensure that every user provides a valid email address and mailing address. Model-level validations are the best way to ensure that only valid data is saved into your database.
So remember folks, validates is for Rails validators (and custom validator classes ending with Validator if that's what you're into), and validate is for your custom validator methods.
Rails validation defines valid states for each of your Active Record model classes. They are used to ensure that only valid details are entered into your database. Rails make it easy to add validations to your model classes and allows you to create your own validation methods as well.
I think you have an error in your syntax:
validates :one, :two, :presence => true, :if => :condition_testing?
def condition_testing?
!(one == 0 && two == 1)
end
There was one :if too many in there...
And if I understand correctly you want to have it only validate in case one == 0 && two == 1
?
Then you condition_testing? is inverted (leave out the !())
If unsure you could try to use pry and insert a breakpoint into your condition_testing?
method to see what's going on.
(Please note added ":" before condition testing)
You can validate it in one line:
validates :one, :two, :presence => true, :if => Proc.new { |a| !(a.one == 0 && a.two == 1) }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With