diff options
Diffstat (limited to 'guides/source/active_record_postgresql.md')
-rw-r--r-- | guides/source/active_record_postgresql.md | 99 |
1 files changed, 54 insertions, 45 deletions
diff --git a/guides/source/active_record_postgresql.md b/guides/source/active_record_postgresql.md index 742db7be32..16c1567c69 100644 --- a/guides/source/active_record_postgresql.md +++ b/guides/source/active_record_postgresql.md @@ -1,4 +1,4 @@ -**DO NOT READ THIS FILE ON GITHUB, GUIDES ARE PUBLISHED ON http://guides.rubyonrails.org.** +**DO NOT READ THIS FILE ON GITHUB, GUIDES ARE PUBLISHED ON https://guides.rubyonrails.org.** Active Record and PostgreSQL ============================ @@ -14,7 +14,7 @@ After reading this guide, you will know: -------------------------------------------------------------------------------- -In order to use the PostgreSQL adapter you need to have at least version 8.2 +In order to use the PostgreSQL adapter you need to have at least version 9.1 installed. Older versions are not supported. To get started with PostgreSQL have a look at the @@ -29,8 +29,8 @@ that are supported by the PostgreSQL adapter. ### Bytea -* [type definition](http://www.postgresql.org/docs/current/static/datatype-binary.html) -* [functions and operators](http://www.postgresql.org/docs/current/static/functions-binarystring.html) +* [type definition](https://www.postgresql.org/docs/current/static/datatype-binary.html) +* [functions and operators](https://www.postgresql.org/docs/current/static/functions-binarystring.html) ```ruby # db/migrate/20140207133952_create_documents.rb @@ -39,7 +39,7 @@ create_table :documents do |t| end # app/models/document.rb -class Document < ActiveRecord::Base +class Document < ApplicationRecord end # Usage @@ -49,8 +49,8 @@ Document.create payload: data ### Array -* [type definition](http://www.postgresql.org/docs/current/static/arrays.html) -* [functions and operators](http://www.postgresql.org/docs/current/static/functions-array.html) +* [type definition](https://www.postgresql.org/docs/current/static/arrays.html) +* [functions and operators](https://www.postgresql.org/docs/current/static/functions-array.html) ```ruby # db/migrate/20140207133952_create_books.rb @@ -63,7 +63,7 @@ add_index :books, :tags, using: 'gin' add_index :books, :ratings, using: 'gin' # app/models/book.rb -class Book < ActiveRecord::Base +class Book < ApplicationRecord end # Usage @@ -83,7 +83,8 @@ Book.where("array_length(ratings, 1) >= 3") ### Hstore -* [type definition](http://www.postgresql.org/docs/current/static/hstore.html) +* [type definition](https://www.postgresql.org/docs/current/static/hstore.html) +* [functions and operators](https://www.postgresql.org/docs/current/static/hstore.html#id-1.11.7.26.5) NOTE: You need to enable the `hstore` extension to use hstore. @@ -97,7 +98,7 @@ ActiveRecord::Schema.define do end # app/models/profile.rb -class Profile < ActiveRecord::Base +class Profile < ApplicationRecord end # Usage @@ -108,21 +109,29 @@ profile.settings # => {"color"=>"blue", "resolution"=>"800x600"} profile.settings = {"color" => "yellow", "resolution" => "1280x1024"} profile.save! + +Profile.where("settings->'color' = ?", "yellow") +# => #<ActiveRecord::Relation [#<Profile id: 1, settings: {"color"=>"yellow", "resolution"=>"1280x1024"}>]> ``` -### JSON +### JSON and JSONB -* [type definition](http://www.postgresql.org/docs/current/static/datatype-json.html) -* [functions and operators](http://www.postgresql.org/docs/current/static/functions-json.html) +* [type definition](https://www.postgresql.org/docs/current/static/datatype-json.html) +* [functions and operators](https://www.postgresql.org/docs/current/static/functions-json.html) ```ruby # db/migrate/20131220144913_create_events.rb +# ... for json datatype: create_table :events do |t| t.json 'payload' end +# ... or for jsonb datatype: +create_table :events do |t| + t.jsonb 'payload' +end # app/models/event.rb -class Event < ActiveRecord::Base +class Event < ApplicationRecord end # Usage @@ -138,8 +147,8 @@ Event.where("payload->>'kind' = ?", "user_renamed") ### Range Types -* [type definition](http://www.postgresql.org/docs/current/static/rangetypes.html) -* [functions and operators](http://www.postgresql.org/docs/current/static/functions-range.html) +* [type definition](https://www.postgresql.org/docs/current/static/rangetypes.html) +* [functions and operators](https://www.postgresql.org/docs/current/static/functions-range.html) This type is mapped to Ruby [`Range`](http://www.ruby-doc.org/core-2.2.2/Range.html) objects. @@ -150,7 +159,7 @@ create_table :events do |t| end # app/models/event.rb -class Event < ActiveRecord::Base +class Event < ApplicationRecord end # Usage @@ -173,7 +182,7 @@ event.ends_at # => Thu, 13 Feb 2014 ### Composite Types -* [type definition](http://www.postgresql.org/docs/current/static/rowtypes.html) +* [type definition](https://www.postgresql.org/docs/current/static/rowtypes.html) Currently there is no special support for composite types. They are mapped to normal text columns: @@ -200,7 +209,7 @@ create_table :contacts do |t| end # app/models/contact.rb -class Contact < ActiveRecord::Base +class Contact < ApplicationRecord end # Usage @@ -213,7 +222,7 @@ contact.save! ### Enumerated Types -* [type definition](http://www.postgresql.org/docs/current/static/datatype-enum.html) +* [type definition](https://www.postgresql.org/docs/current/static/datatype-enum.html) Currently there is no special support for enumerated types. They are mapped as normal text columns: @@ -239,7 +248,7 @@ def down end # app/models/article.rb -class Article < ActiveRecord::Base +class Article < ApplicationRecord end # Usage @@ -251,7 +260,7 @@ article.status = "published" article.save! ``` -To add a new value before/after existing one you should use [ALTER TYPE](http://www.postgresql.org/docs/current/static/sql-altertype.html): +To add a new value before/after existing one you should use [ALTER TYPE](https://www.postgresql.org/docs/current/static/sql-altertype.html): ```ruby # db/migrate/20150720144913_add_new_state_to_articles.rb @@ -265,9 +274,9 @@ def up end ``` -NOTE: ENUM values can't be dropped currently. You can read why [here](http://www.postgresql.org/message-id/29F36C7C98AB09499B1A209D48EAA615B7653DBC8A@mail2a.alliedtesting.com). +NOTE: ENUM values can't be dropped currently. You can read why [here](https://www.postgresql.org/message-id/29F36C7C98AB09499B1A209D48EAA615B7653DBC8A@mail2a.alliedtesting.com). -Hint: to show all the values of the all enums you have, you should call this query in `bin/rails db` or `psql` console: +Hint: to show all the values of the all enums you have, you should call this query in `rails db` or `psql` console: ```sql SELECT n.nspname AS enum_schema, @@ -280,9 +289,9 @@ SELECT n.nspname AS enum_schema, ### UUID -* [type definition](http://www.postgresql.org/docs/current/static/datatype-uuid.html) -* [pgcrypto generator function](http://www.postgresql.org/docs/current/static/pgcrypto.html#AEN159361) -* [uuid-ossp generator functions](http://www.postgresql.org/docs/current/static/uuid-ossp.html) +* [type definition](https://www.postgresql.org/docs/current/static/datatype-uuid.html) +* [pgcrypto generator function](https://www.postgresql.org/docs/current/static/pgcrypto.html#id-1.11.7.35.7) +* [uuid-ossp generator functions](https://www.postgresql.org/docs/current/static/uuid-ossp.html) NOTE: You need to enable the `pgcrypto` (only PostgreSQL >= 9.4) or `uuid-ossp` extension to use uuid. @@ -294,7 +303,7 @@ create_table :revisions do |t| end # app/models/revision.rb -class Revision < ActiveRecord::Base +class Revision < ApplicationRecord end # Usage @@ -317,12 +326,12 @@ create_table :comments, id: :uuid, default: 'gen_random_uuid()' do |t| end # app/models/post.rb -class Post < ActiveRecord::Base +class Post < ApplicationRecord has_many :comments end # app/models/comment.rb -class Comment < ActiveRecord::Base +class Comment < ApplicationRecord belongs_to :post end ``` @@ -331,8 +340,8 @@ See [this section](#uuid-primary-keys) for more details on using UUIDs as primar ### Bit String Types -* [type definition](http://www.postgresql.org/docs/current/static/datatype-bit.html) -* [functions and operators](http://www.postgresql.org/docs/current/static/functions-bitstring.html) +* [type definition](https://www.postgresql.org/docs/current/static/datatype-bit.html) +* [functions and operators](https://www.postgresql.org/docs/current/static/functions-bitstring.html) ```ruby # db/migrate/20131220144913_create_users.rb @@ -340,8 +349,8 @@ create_table :users, force: true do |t| t.column :settings, "bit(8)" end -# app/models/device.rb -class User < ActiveRecord::Base +# app/models/user.rb +class User < ApplicationRecord end # Usage @@ -355,7 +364,7 @@ user.save! ### Network Address Types -* [type definition](http://www.postgresql.org/docs/current/static/datatype-net-types.html) +* [type definition](https://www.postgresql.org/docs/current/static/datatype-net-types.html) The types `inet` and `cidr` are mapped to Ruby [`IPAddr`](http://www.ruby-doc.org/stdlib-2.2.2/libdoc/ipaddr/rdoc/IPAddr.html) @@ -370,7 +379,7 @@ create_table(:devices, force: true) do |t| end # app/models/device.rb -class Device < ActiveRecord::Base +class Device < ApplicationRecord end # Usage @@ -390,7 +399,7 @@ macbook.address ### Geometric Types -* [type definition](http://www.postgresql.org/docs/current/static/datatype-geometric.html) +* [type definition](https://www.postgresql.org/docs/current/static/datatype-geometric.html) All geometric types, with the exception of `points` are mapped to normal text. A point is casted to an array containing `x` and `y` coordinates. @@ -410,7 +419,7 @@ create_table :devices, id: :uuid, default: 'gen_random_uuid()' do |t| end # app/models/device.rb -class Device < ActiveRecord::Base +class Device < ApplicationRecord end # Usage @@ -418,7 +427,7 @@ device = Device.create device.id # => "814865cd-5a1d-4771-9306-4268f188fe9e" ``` -NOTE: `uuid_generate_v4()` (from `uuid-ossp`) is assumed if no `:default` option was +NOTE: `gen_random_uuid()` (from `pgcrypto`) is assumed if no `:default` option was passed to `create_table`. Full Text Search @@ -431,10 +440,10 @@ create_table :documents do |t| t.string 'body' end -execute "CREATE INDEX documents_idx ON documents USING gin(to_tsvector('english', title || ' ' || body));" +add_index :documents, "to_tsvector('english', title || ' ' || body)", using: :gin, name: 'documents_idx' # app/models/document.rb -class Document < ActiveRecord::Base +class Document < ApplicationRecord end # Usage @@ -448,7 +457,7 @@ Document.where("to_tsvector('english', title || ' ' || body) @@ to_tsquery(?)", Database Views -------------- -* [view creation](http://www.postgresql.org/docs/current/static/sql-createview.html) +* [view creation](https://www.postgresql.org/docs/current/static/sql-createview.html) Imagine you need to work with a legacy database containing the following table: @@ -484,7 +493,7 @@ CREATE VIEW articles AS SQL # app/models/article.rb -class Article < ActiveRecord::Base +class Article < ApplicationRecord self.primary_key = "id" def archive! update_attribute :archived, true @@ -499,9 +508,9 @@ second = Article.create! title: "Brace yourself", status: "draft", published_at: 1.month.ago -Article.count # => 1 -first.archive! Article.count # => 2 +first.archive! +Article.count # => 1 ``` NOTE: This application only cares about non-archived `Articles`. A view also |