0

I have a model. In some cases I need to validate all its fields for presence and another kinds of stuff, in other cases I need to validate only some of them and other fields can remain empty. What's the best way to achieve this?

  • 1
    Possible duplicate of [Rails conditional validation in model](http://stackoverflow.com/questions/24641143/rails-conditional-validation-in-model) – Brad Werth Jun 02 '16 at 05:28

2 Answers2

5

Check this

validates_presence_of :state, :if => :in_us?

def in_us?
  country == 'US'
end

Here it validates presence of state only if country is US. For other country id dosen't validates state.

For detail: http://railscasts.com/episodes/41-conditional-validations

Ganesh Kunwar
  • 2,643
  • 2
  • 20
  • 36
-2

You could use conditional validation.Please refer the doc http://guides.rubyonrails.org/active_record_validations.html#5.1

tessie
  • 964
  • 3
  • 14
  • 24