Skip to content

Instantly share code, notes, and snippets.

@Electron-libre
Created October 16, 2013 13:22
This is an example of Postgres Array use with Rails 4.
class CreateRoles < ActiveRecord::Migration
def change
create_table :roles do |t|
t.string :activities, array: true, length: 30, using: 'gin', default: '{}'
t.timestamps
end
end
end
##
# You can use it since ActiveRecord 4
#
# 'array: true' is the arryfication
# 'length : 30' applies to the string in array
# 'using: "gin"' is the index strategy for faster lookup and slower writes see: http://www.postgresql.org/docs/9.1/static/textsearch-indexes.html
# 'default: "{}"' is the default value ( same as [] )
#
# [2] pry(main)> r = Role.last
# Role Load (0.7ms) SELECT "roles".* FROM "roles" ORDER BY "roles"."id" DESC LIMIT 1
# => #<Role id: 2, activities: ["person:show"], created_at: "2013-10-15 13:21:06", updated_at: "2013-10-15 13:21:06">
#
# [17] pry(main)> r.activities += %w(person:delete person:update)
# => ["person:show", "person:delete", "person:update"]
# [18] pry(main)> r.save
# (0.3ms) BEGIN
# SQL (4.1ms) UPDATE "roles" SET "activities" = $1, "updated_at" = $2 WHERE "roles"."id" = 2 [["activities", ["person:show", # "person:delete", "person:update"]], ["updated_at", Wed, 16 Oct 2013 13:12:12 UTC +00:00]]
# (2.3ms) COMMIT
# => true
#
# [25] pry(main)> r.activities = r.activities[0,2]
# => ["person:show", "person:delete"]
# [26] pry(main)> r.save
# (0.4ms) BEGIN
# SQL (0.8ms) UPDATE "roles" SET "activities" = $1, "updated_at" = $2 WHERE "roles"."id" = 2 [["activities", ["person:show", # "person:delete"]], ["updated_at", Wed, 16 Oct 2013 13:16:01 UTC +00:00]]
# (8.0ms) COMMIT
# => true
#
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment