Custom Rails Model Validation

I have an attribute ( :book) in my database that I would like to limit the three different values of →> :classic, :modern,:historic

I want to create a custom check so that when it is created or updated, the user cannot enter googly-moogly

book: classic
      modern
      historic
+4
source share
2 answers

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.

+4
source

Update from @travis

:

acceptance, :accept, , .

:

class library < ActiveRecord::Base
  validates :book, acceptance: { accept: 'some value' }
end

* *

Rails Validations

@Travis @MrYoshiji, , , VALID_BOOKS = [:classic, :modern, :historic]

:

validates :book, inclusion: { in: VALID_BOOKS.map(&:to_s) }
0

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


All Articles