devroom.io/content/posts/2008-08-17-activerecord-read-only-models.md

48 lines
1.4 KiB
Markdown
Raw Normal View History

2015-03-26 11:28:08 +00:00
+++
date = "2008-08-17"
title = "ActiveRecord Read Only Model"
tags = ["General", "Blog", "Ruby", "Rails", "ror", "activerecord"]
slug = "activerecord-read-only-models"
+++
ActiveRecord is great in providing CRUD for your data models. In some cases, however, it's necessary to prevent write access to these models. The data may be provided by an external source and should only be used as a reference in your application, for example.
I'm going to show you how you can easily mark a Model as read only all the time. In this example I have a Item model like this:
2017-03-20 15:35:19 +00:00
``` ruby
class Item < ActiveRecord::Base
end
```
2015-03-26 11:28:08 +00:00
ActiveRecord::Base provides two methods that may be of interest here:
2017-03-20 15:35:19 +00:00
``` ruby
def readonly!
2015-03-26 11:28:08 +00:00
@readonly = true
end
def readonly?
defined?(@readonly) && @readonly == true
2017-03-20 15:35:19 +00:00
end
```
2015-03-26 11:28:08 +00:00
The first method sets the record to read only. This is great, but we don't want to set the read only property every time we load a model. The second, readonly?, return true if the object is read only or false if it isn't.
So, if we return true on the readonly? method, our object is marked as read only. Great!
2017-03-20 15:35:19 +00:00
``` ruby
class Item < ActiveRecord::Base
2015-03-26 11:28:08 +00:00
def readonly?
true
end
2017-03-20 15:35:19 +00:00
end
```
2015-03-26 11:28:08 +00:00
That is all! All Item objects are now marked as read only all the time. If you try to write to the model, you'll receive an error.
2017-03-20 15:35:19 +00:00
``` ruby
item = Item.find(:first)
2015-03-26 11:28:08 +00:00
item.update_attributes(:name => 'Some item name')
2017-03-20 15:35:19 +00:00
=> ActiveRecord::RecordReadOnly
```