Skip to content

Instantly share code, notes, and snippets.

@fdutey
Created April 27, 2009 13:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fdutey/102477 to your computer and use it in GitHub Desktop.
Save fdutey/102477 to your computer and use it in GitHub Desktop.
#lib/active_record/custom_validations.rb
module ActiveRecord
module CustomValidations
def validates_unchanged_value(*attr_names)
configuration = { :message => :frozen_attribute }
configuration.update(attr_names.extract_options!)
configuration[:on] = :update
validates_each(attr_names, configuration) do |record, attr_name, value|
record.errors.add(attr_name, :frozen_attribute, :default => configuration[:message]) if record.send("#{attr_name}_changed?")
end
end
end
end
ActiveRecord::Base.send(:extend, ActiveRecord::CustomValidations)
#app/models/post.rb
class Post < ActiveRecord::Base
#...
validates_unchanged_value :title, :if => :published?,
:message => :frozen_attribute_when_published
end
#script/console
>> a = Post.first(:conditions => { :published => true })
=> #<Post ... >
>> a.update_attributes(:title => "test 1234")
=> false
>> a.errors
=> #<ActiveRecord::Errors:: ... @errors => {"title" => ["translation missing: ... frozen_attribute_when_published"
>> a = Post.first(:conditions => { :published => false })
=> #<Post ... >
>> a.update_attributes(:title => "test 1234")
=> true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment