Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validates with :if

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
like image 715
James Avatar asked Dec 16 '11 12:12

James


People also ask

What are validations in Rails?

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.

What is the difference between validate and validates in rails?

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.

How does validation work in Rails?

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.


2 Answers

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)

like image 191
Tigraine Avatar answered Oct 04 '22 05:10

Tigraine


You can validate it in one line:

validates :one, :two, :presence => true, :if => Proc.new { |a| !(a.one == 0 && a.two == 1) }
like image 34
potashin Avatar answered Oct 04 '22 03:10

potashin