Olly Legg home

Strict Validations in ActiveModel

27 Feb 2012

Rails v3.2 has added the concept of strict validations. These validations are ideally suited for data constraints which should always be enforced, but aren't affected by user input. For example, setting the user association to the current_user in the controller.

There are two ways of specifying a validation as strict. Firstly, you can set the :strict option to true. Secondly, you can use the new validates! method.

An ActiveModel::StrictValidationFailed exception is raised if your record fails validation.

class Content
  validates_presence_of :user, strict: true

  # The following is equivalent: 
  # validates! :user, presence: true

content = Content.new
content.user = nil
# => ActiveModel::StrictValidationFailed: can't be blank