aboutsummaryrefslogtreecommitdiffstats
path: root/guides/source/active_record_postgresql.md
diff options
context:
space:
mode:
authorYves Senn <yves.senn@gmail.com>2014-05-11 13:47:30 +0200
committerYves Senn <yves.senn@gmail.com>2014-05-11 13:47:30 +0200
commitdf8a1b25d42a7ea97aa812ca46b570bdb618cba5 (patch)
tree81f09bf2dd8572348ebcaa45287f4c7449839f84 /guides/source/active_record_postgresql.md
parentadcba34c57adba61bfaf45296a6dc707c8338b99 (diff)
downloadrails-df8a1b25d42a7ea97aa812ca46b570bdb618cba5.tar.gz
rails-df8a1b25d42a7ea97aa812ca46b570bdb618cba5.tar.bz2
rails-df8a1b25d42a7ea97aa812ca46b570bdb618cba5.zip
pg guide, PostgreSQL legacy table view example. [ci skip]
Diffstat (limited to 'guides/source/active_record_postgresql.md')
-rw-r--r--guides/source/active_record_postgresql.md59
1 files changed, 59 insertions, 0 deletions
diff --git a/guides/source/active_record_postgresql.md b/guides/source/active_record_postgresql.md
index fddfe24abb..14f7f4dccd 100644
--- a/guides/source/active_record_postgresql.md
+++ b/guides/source/active_record_postgresql.md
@@ -371,3 +371,62 @@ Document.where("to_tsvector('english', title || ' ' || body) @@ to_tsquery(?)",
Views
-----
+
+* [view creation](http://www.postgresql.org/docs/9.3/static/sql-createview.html)
+
+Imagine you need to work with a legacy database containing the following table:
+
+```
+rails_pg_guide=# \d "TBL_ART"
+ Table "public.TBL_ART"
+ Column | Type | Modifiers
+------------+-----------------------------+------------------------------------------------------------
+ INT_ID | integer | not null default nextval('"TBL_ART_INT_ID_seq"'::regclass)
+ STR_TITLE | character varying |
+ STR_STAT | character varying | default 'draft'::character varying
+ DT_PUBL_AT | timestamp without time zone |
+ BL_ARCH | boolean | default false
+Indexes:
+ "TBL_ART_pkey" PRIMARY KEY, btree ("INT_ID")
+```
+
+This table does not follow the Rails conventions at all.
+Because simple PostgreSQL views are updateable by default,
+we can wrap it as follows:
+
+```ruby
+# db/migrate/20131220144913_create_articles_view.rb
+execute <<-SQL
+CREATE VIEW articles AS
+ SELECT "INT_ID" AS id,
+ "STR_TITLE" AS title,
+ "STR_STAT" AS status,
+ "DT_PUBL_AT" AS published_at,
+ "BL_ARCH" AS archived
+ FROM "TBL_ART"
+ WHERE "BL_ARCH" = 'f'
+ SQL
+
+# app/models/article.rb
+class Article < ActiveRecord::Base
+ self.primary_key = "id"
+ def archive!
+ update_attribute :archived, true
+ end
+end
+
+# Usage
+first = Article.create! title: "Winter is coming",
+ status: "published",
+ published_at: 1.year.ago
+second = Article.create! title: "Brace yourself",
+ status: "draft",
+ published_at: 1.month.ago
+
+Article.count # => 1
+first.archive!
+p Article.count # => 2
+```
+
+Note: This application only cares about non-archived `Articles`. A view also
+allows for conditions so we can exclude the archived `Articles` directly.