From 1f14a12fc94ca133cdab1aec17a1cca76765c664 Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Fri, 10 Jun 2016 08:21:43 -0500 Subject: [PATCH] Add Read-Only Models as a rails til --- README.md | 3 ++- rails/read-only-models.md | 23 +++++++++++++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) create mode 100644 rails/read-only-models.md diff --git a/README.md b/README.md index 3b06f3f..a73f516 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,7 @@ variety of languages and technologies. These are things that don't really warrant a full blog post. These are mostly things I learn by pairing with smart people at [Hashrocket](http://hashrocket.com/). -_431 TILs and counting..._ +_432 TILs and counting..._ --- @@ -278,6 +278,7 @@ _431 TILs and counting..._ - [Params Includes Submission Button Info](rails/params-includes-submission-button-info.md) - [Perform SQL Explain With ActiveRecord](rails/perform-sql-explain-with-activerecord.md) - [Pretend Generations](rails/pretend-generations.md) +- [Read-Only Models](rails/read-only-models.md) - [Rescue From](rails/rescue-from.md) - [Retrieve An Object If It Exists](rails/retrieve-an-object-if-it-exists.md) - [Select A Select By Selector](rails/select-a-select-by-selector.md) diff --git a/rails/read-only-models.md b/rails/read-only-models.md new file mode 100644 index 0000000..16b430b --- /dev/null +++ b/rails/read-only-models.md @@ -0,0 +1,23 @@ +# Read-Only Models + +Are you in the midst of a big refactoring that is phasing out an +`ActiveRecord` model? You may not be ready to wipe it from the project, but +you don't want it accidentally used to create any database records. You +essentially want your model to be read-only until it is time to actually +delete it. + +This can be achieved by adding a `readonly?` method to that model that +always returns `true`. + +```ruby +def readonly? + true +end +``` + +`ActiveRecord`'s underlying persistence methods always check `readonly?` +before creating or updating any records. + +[source](http://stackoverflow.com/questions/5641410/is-there-an-easy-way-to-make-a-rails-activerecord-model-read-only) + +h/t Josh Davey