Narrowing conditional validation in a Ruby class

How can I drain my verification code? I have a Discussion model that has category and status fields. The status value depends on the category value. A discussion in which category == 'question' can only be STATUSES[:question] .

  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 am using Rails 3.

+4
source share
1 answer

:inclusion :in accepts lambda itself:

 validates :status, inclusion: { in: lambda { |o| STATUSES[o.category.to_sym] } } 

Documentation: http://apidock.com/rails/ActiveModel/Validations/HelperMethods/validates_inclusion_of

+5
source

Source: https://habr.com/ru/post/1442357/


All Articles