Skip to content

Defining change set validations

E. Lynette Rayle edited this page Oct 23, 2020 · 10 revisions

back to Introduction

Goals

  • Understand validations with Change Sets.
  • Introduce validations into the Book Change Set.
  • Define a custom validator.

Reference: ActiveRecord validations

Types of validations

Supports validations through ActiveModel validations. Not all ActiveRecord validations are supported (e.g. uniqueness is not supported). Some common examples are...

  • validates property_name, property_name, ..., presence - passes if the property or list of properties all have values present
  • validates_with ClassName[, property: property_name] - calls #validate method in the identified class to determine if the property's value is valid; if no property_name is identified, it is used to validate the change set as a whole

Specifying validations

Add validations to Book's change set

  • add presence validation for title and author fields
  • add custom validator that validates the series field

Edit app/change_sets/book_change_set.rb and add validations so that the file contains the following:

# frozen_string_literal: true
require 'validators/series_validator'

class BookChangeSet < Valkyrie::ChangeSet
  property :title, multiple: true, required: true
  property :author, multiple: true, required: true
  property :series, multiple: false, required: false
  property :member_ids, multiple: true, required: false

  validates :title, :author, presence: true # standard presence validator
  validates_with SeriesValidator            # custom validator defined below in the SeriesValidator class
end
info_16 The entire change set will be passed to the validator, not just the series field that is being validated by the SeriesValidator.

Define custom validator class

Create the directory app/validators inside your project directory. Edit app/change_sets/series_validator.rb to contain the following:

# frozen_string_literal: true
class SeriesValidator < ActiveModel::Validator
  # ensure the property exists and is in the controlled vocabulary
  def validate(record)
    valid = ['Joe Pike', 'Elvis Cole', 'Elvis Cole/Joe Pike'].include? record.series
    return true if valid
    record.errors.add :series, "#{record.series} is not a valid series"
  end
end

Previous | Next