Wednesday 29 February 2012

Strict Validations in ActiveModel/Rails v3.2 has added the concept of strict validations


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 :strictoption 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
end

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

No comments:

Post a Comment