How can I dry up my validation code? I have a Discussion model that has a a category and status fields. The status value depends on the category value. A discussion where category == 'question' can only have a status in STATUSES[:question], for example.
STATUSES = {
question: %w[answered],
suggestion: %w[pending planned started completed declined],
problem: %w[started solved]
}
validates :status, allow_blank: true, inclusion: { in: STATUSES[:question] }, if: lambda { self.category == 'question' }
validates :status, allow_blank: true, inclusion: { in: STATUSES[:suggestion] }, if: lambda { self.category == 'suggestion' }
validates :status, allow_blank: true, inclusion: { in: STATUSES[:problem] }, if: lambda { self.category == 'problem' }
I’m using Rails 3.
:inclusion :inaccepts a lambda itself:Documentation: http://apidock.com/rails/ActiveModel/Validations/HelperMethods/validates_inclusion_of