Jump To Content

LearnHub




Using the Immutable Attribute Plugin

Rails surprisingly does not include a validation method to make a model attribute immutable. (That is, the attribute can not be changed after it is set the first time.) I created this validation plugin to help that.

To install:


 script/plugin install git://github.com/wmoxam/immutable-attribute-plugin.git

To use, drop this in your model:


 ensures_immutability_of :attribute_name

You can specify multiple immutable attributes in one line:


 ensures_immutability_of :attribute1, :attribute2

Now if something attempts to set a protected attribute, it will raise an error. For example:


class Account < ActiveRecord::Base
 ensures_immutability_of :username, :email
end

account = Account.create(:username => 'jgreen')
...
account.update(:username => 'jgreen') # raises ActiveRecord::ImmutableAttributeError

This plugin works especially nicely with the "Email Veracity Plugin": If you have an email-verification process (such as sending an activation email) then you will most likely want to mark the email attribute as immutable, and create new records for when users add other email addresses.

But this is probably most excellent for username and relationship attributes (foreign key fields). That is exactly how we are using it on Languify


  1. mxavier saidThu, 27 Nov 2008 03:28:28 -0000 ( Link )

    I’m fairly new to installing plugins but when I try to run rake tasks on my app after installing your plugin I get:

    Plugins::Immutable-attribute-plugin::Lib” is not a valid constant name!

    Actions
    Vote
    Current Rating
    0
    Rate Up
    Rate Down
    No Votes

    Post Comments

Your Comment
Textile is Enabled (View Reference)