Module: Sequel::Plugins::PgArrayAssociations

Defined in:
lib/sequel/plugins/pg_array_associations.rb

Overview

This plugin allows you to create associations where the foreign keys are stored in a PostgreSQL array column in one of the tables. The model with the table containing the array column has a pg_array_to_many association to the associated model, and the model with the table containing the primary key referenced by elements in the array column has a many_to_pg_array association to the associated model.

# Database schema:
#   tags                albums
#   :id (int4) <--\    :id
#   :name          \-- :tag_ids (int4[])
#                      :name

class Album
  plugin :pg_array_associations
  pg_array_to_many :tags
end
class Tag
  plugin :pg_array_associations
  many_to_pg_array :albums
end

These association types work similarly to Sequel’s other association types, so you can use them as you would any other association. Unlike other associations, they do not support composite keys.

One thing that is different is that the modification methods for pg_array_to_many associations do not affect the database, since they operate purely on the receiver. For example:

album = Album[1]
album.add_tag(Tag[2])

does not save the album. This allows you to call add_tag repeatedly and the save after to combine all changes into a single query. Note that the many_to_pg_array association modification methods do save, so:

tag = Tag[2]
tag.add_album(Album[1])

will save the changes to the album.

They support some additional options specific to this plugin:

:array_type

This overrides the type of the array. By default, the type is determined by looking at the db_schema for the model, and if that fails, it defaults to :integer.

:raise_on_save_failure

Do not raise exceptions for hook or validation failures when saving associated objects in the add/remove methods (return nil instead).

:save_after_modify

For pg_array_to_many associations, this makes the the modification methods save the current object, so they operate more similarly to the one_to_many and many_to_many association modification methods.

:uniq

Similar to many_to_many associations, this can be used to make sure the returned associated object array has uniq values.

Note that until PostgreSQL gains the ability to enforce foreign key constraints in array columns, this plugin is not recommended for production use unless you plan on emulating referential integrity constraints via triggers.

This plugin should work on all supported PostgreSQL versions, except the remove_all modification method for many_to_pg_array associations, which requires the array_remove method added in PostgreSQL 9.3.

This plugin requires that the underlying database have the pg_array extension loaded.

Defined Under Namespace

Modules: ClassMethods, DatasetMethods Classes: ManyToPgArrayAssociationReflection, PgArrayToManyAssociationReflection