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
Page Author
From Here You Can…
Information
- 825 Views
- 0 Comments
Most Recent Related Content
- Lesson
- Avatar

- Title
- Nginx + HaProxy usage and a gotcha
- Body
- I’ve recently switched from using a straight up Apache mod_proxy + mong...
- Author
- Lesson
- Avatar

- Title
- Ruby on Rails实践(4)--- 做一个出来看看
- Body
- 总算到了这激动人心的一步了。 注...
- Author
- Lesson
- Avatar

- Title
- Upgrading non-trivial apps to Rails 2.1
- Body
- For simple Ruby on Rails apps that use very few plugins, upgrading may be as ...
- Author
- Video
- Avatar

- Title
- Ruby Metaclasses - Session 3
- Description
- Author
- Lesson
- Avatar

- Title
- Ruby on Rails实践(1)---我们需要J2EE吗
- Body
- 如果你作为一个Java 程序员从事j2ee开发的话,你一定会使用到众多应用程序框架。没有任何...
- Author
- Video
- Avatar

- Title
- Ruby Basics - Session 3
- Description
- Ruby Basics Screen Cast—Session 3
- Author
- Video
- Avatar

- Title
- Ruby Metaclasses - Session 6
- Description
- Author
- Lesson
- Avatar

- Title
- Calling partials through helpers
- Body
- Rails partials are are fragments of template code that can be inserted into ...
- Author