Created
April 27, 2009 13:02
-
-
Save fdutey/102476 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
>> 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Post < ActiveRecord::Base | |
#... | |
validates_unchanged_value :title, :if => published?, | |
:message => :frozen_attribute_when_published | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment