Validates Constancy plugin

Plugin details

This RubyGem and Rails plugin adds a validates_constancy_of validation to Active Record. It allows you to prevent particular database fields from being changed after a record is created. A validation error occurs on updates if an attribute of a model object is different from its value in the database.

Websitehttp://constancy.rubyforge.org/ Repositoryhttp://constancy.rubyforge.org/svn/plugin/validates_constancy Author Nils Jonsson Tags validation LicenseMIT

Documentation

Install the plugin:
ruby script/plugin install http://constancy.rubyforge.org/svn/plugin/validates_constancy

Here's how to use this validation in your code.

class Person < ActiveRecord::Base
  
  # Prevent changes to Person#social_security_number.
  validates_constancy_of :social_security_number
  
end



OPTIONS

The validation takes two options, :if and :message. These may be familiar because several of Active Record's validations also use them. The :if option takes a Proc, or a symbol, or string with a model object argument and a return value of true or false.

class Comment < ActiveRecord::Base
  
  # Prevent changes to Comment#text if it is "locked."
  validates_constancy_of :text, :if => Proc.new { |comment| comment.locked? }
  
end



The default error message is "can't be changed". Use your own error message by specifying the :message option.

class LicensePlate < ActiveRecord::Base
  
  # Prevent changes to LicensePlate#number.
  validates_constancy_of :number,
                         :message => 'is off-limits! What are you thinking?'
  
end



More than one model attribute can be specified. Any specified options will be applied to all the specified attributes.

WARNING

With associations, validate the constancy of a foreign key, not the instance variable itself: 'validates_constancy_of :invoice_id' instead of 'validates_constancy_of :invoice'.

Also note the warning under Inheritable callback queues in http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html. "In order for inheritance to work for the callback queues, you must specify the callbacks before specifying the associations. Otherwise, you might trigger the loading of a child before the parent has registered the callbacks and they won't be inherited." Validates Constancy uses these callback queues, so you'll want to specify associations *after* 'validates_constancy_of' statements in your model classes.

Further Documentation

There is currently no advanced documentation for this plugin.

New documentation

Edit plugin | Back in time (4 older versions) | Last edited by: njonsson, 8 months ago