Mark Daggett's Blog

Innovator & Bricoleur

Simple Rails 3 Validator for Unchangeable Attributes

Here is a simple Rails validator that you can use to ensure an attribute of a model cannot be changed once it has been assigned a value.

1
2
3
4
5
6
7
8
9
10
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

You can use it this way:

1
validates :email, :unchangeable => true, :presence => true

Here are some specs to prove it works:

1
2
3
4
5
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

Like this post, then you'll love my book on JavaScript.

Expert JavaScript is your definitive guide to understanding how and why JavaScript behaves the way it does. Master the inner workings of JavaScript by learning in detail how modern applications are made. In covering lesser-understood aspects of this powerful language and truly understanding how it works, your JavaScript code and programming skills will improve.

Comments