Class: ReferenceValidator

Inherits:
ActiveModel::EachValidator
  • Object
show all
Defined in:
lib/tram/validators/reference_validator.rb

Overview

Checks that a model instance can be found by id

Examples:

Checks that AdminPolicy.new(user).valid?

validates :user_key, reference: { model: User, find_by: :key }

Instance Method Summary collapse

Instance Method Details

#validate_each(record, attribute, value) ⇒ Object



7
8
9
10
11
12
13
# File 'lib/tram/validators/reference_validator.rb', line 7

def validate_each(record, attribute, value)
  model = options.fetch(:model) { raise "You should define :model option" }
  key   = options.fetch(:find_by, :id)

  return if model.find_by(key => value)
  record.errors.add attribute, :not_found
end