Skip to content

Instantly share code, notes, and snippets.

@fdutey fdutey/gist:102477
Created Apr 27, 2009

Embed
What would you like to do?
#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
You can’t perform that action at this time.