Any model has a book attribute:
VALID_BOOKS = [:classic, :modern, :historic]
validate :has_valid_book
def has_valid_book
return if VALID_BOOKS.include? book.to_sym
errors.add :book, 'must be a valid book'
end
Edit
Thanks to Mr. Yoshiji, pointing out that this particular case can be simplified to
VALID_BOOKS = [:classic, :modern, :historic]
validates :book, inclusion: { in: VALID_BOOKS.map(&:to_s) }
I will leave a more detailed example above if your checks become more complex in the future (as often happens), and an actual method is needed to solve the problem.
source
share