Skip to content

Instantly share code, notes, and snippets.

@kiela
Created December 12, 2013 11:23
Show Gist options
  • Save kiela/7926550 to your computer and use it in GitHub Desktop.
Save kiela/7926550 to your computer and use it in GitHub Desktop.
# 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