0

I validate fields in model using:

validates :first_name, :presence => true, :if => :should_validate?
validates :last_name, :presence => true, :if => :should_validate?
...

There are many fields in model that needs to be validated and it doesn't look good if I specify :if => method for each one.

Is it possible to embed this validates methods in block instead of giving :if => method for each one?

3 Answers 3

1

You could write your own custom validator of course, but if you're only validating presence, this might do the trick:

validates :first_name, :last_name, :presence => true, :if => :should_validate?
Sign up to request clarification or add additional context in comments.

1 Comment

There are many fields in this model, some of them also validates format.
0

I don't think there is something out of the box for this. If you want, you can use a custom validator.

Comments

0

What are the conditions that you need this validated? If you don't need it validated couldn't you just leave that line out? Otherwise you could just validate on certain actions so you don't need to evaluate for should_validate?, for example:

validates :first_name, :last_name, :presence => true, :only => [:create, :update]

1 Comment

should_validate method checks one of the model's field so :only => option will not work here.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.