Created
December 12, 2013 11:23
-
-
Save kiela/7926550 to your computer and use it in GitHub Desktop.
This file contains 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
# validator | |
class UnchangeableValidator < ActiveModel::EachValidator | |
def validate_each(object, attribute, value) | |
if !object.new_record? && value.present? | |
original = object.class.send(:where, "id = #{object.id}").select("id, #{attribute.to_s}").first | |
if original.send(attribute) != value | |
object.errors[attribute] << (options[:message] || "cannot be changed once assigned") | |
end | |
end | |
end | |
end | |
# model | |
validates :email, :unchangeable => true, :presence => true | |
# spec | |
it "should not allow you to change an email for an existing record" do | |
@user.email = "test@test.com" | |
@user.save | |
@user.errors[:email].first.should == "cannot be changed once assigned" | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment